2013-04-01 41 views
0

我試圖顯示當前用戶名一旦被登錄它會說,頁面的頂部顯示,鑑於當前用戶。通過一個多態關聯

因此「已登錄帕特里克」。然而,我有一個多態關聯設置,每個註冊的用戶都是玩家或教練。

由於教練和球員都打網球,該多態關聯屬於標籤或:tennis_player。

該視圖的代碼如下。

<div class="container"> 
    <header> 

    <div class="logo"> 
     <%= link_to(image_tag 'tennis_ball.png', :width => 100, :height => 100) %> 
    </div> 
    <div class="slogan"> 
     <h3>Setfortennis</h3> 
    </div> 


    <div id="user_nav"> 
    <% if current_user? %> 
     Logged in as <%= @current_user %> 

     <%= link_to "log out", log_out_path %> 
    <% else %> 
     <%= link_to "Sign Up", sign_up_path %> or 
     <%= link_to "Log in", log_in_path %> 
    <% end %> 
</div> 

    </header> 
</div> 

這裏是我的應用程序控制器

helper_method :current_user? 

    before_filter :get_user 

    def current_user? 
    !!current_user 
    end 

    def current_user 
    @current_user ||= session[:user_id] && 
     User.find_by_id(session[:user_id]) 
    end 

    def check_logged_in 
    redirect_to(new_session_path, :notice => "You must be logged in to do that!") unless current_user? 
    end 

    def get_user 
    @user = User.new 
    end 
end 

這裏是我的模型。還有什麼需要解決讓我知道!

class Player < ActiveRecord::Base 
    attr_accessible :about, :club, :first_name, :last_name, :profile_picture, :racket, :ranking, :image 

    has_attached_file :image, styles: { 
    thumb: '100x100>', 
    square: '200x200#', 
    medium: '300x300>' 
    } 

    has_many :videos 

    has_one :user, :as => :tennis_player 

end 


    class Coach < ActiveRecord::Base 
    attr_accessible :about, :club, :first_name, :last_name, :profile_picture, :ranking 

    has_one :user, :as => :tennis_player 
end 

用戶模型。

class User < ActiveRecord::Base 
    attr_accessible :email, :password_hash, :password_salt, :password, :password_confirmation 
    attr_accessor :password 

    belongs_to :tennis_player, :polymorphic => true 

    before_save :encrypt_password 

    validates_confirmation_of :password 
    validates_confirmation_of :password, :on => :create 
    validates_confirmation_of :email 
    validates_uniqueness_of :password 

    def self.authenticate(email, password) 
    user = find_by_email(email) 
    if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt) 
     user 
    else 
     nil 
    end 
    end 

    def encrypt_password 
    if password.present? 
     self.password_salt = BCrypt::Engine.generate_salt 
     self.password_hash = BCrypt::Engine.hash_secret(password, password_salt) 
    end 
    end 
end 
+0

什麼在您的用戶模型? –

+0

你好康斯坦丁, 我已經在上面添加了我的用戶模型。你怎麼看? – PatGW

+0

我不明白,current_user.tennis_player.last_name是否適用於您的視圖? –

回答

0

您只需在創建會話時存儲正確的ID。但我會稍微改變一下設計。您可以創建基類User並從中繼承,而不是爲Player和Coach分配兩個單獨的表。

class User < ActiveRecord::Base 
    attr_accessible :about, :club, :first_name, :last_name, :profile_picture, :ranking 
end 

class Player < User 
end 

class Coach < User 
end