ruby - Displaying Current User in view through a polymorphic association -
i attempting display current users name once logged in.
therefore @ top of page "logged in patrick". have polymorphic association set whereby every user signs either player or coach.
the polymorphic association under label or :tennis_player both coach , player play tennis.
the code view below.
<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 <%= @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>
here application controller
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 logged in that!") unless current_user? end def get_user @user = user.new end end
and here models. else needed solve let me know!
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
user model.
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
you need store right id whenever create session. change design little. instead of having 2 separate tables player , coach, can create base class user, , inherit it.
class user < activerecord::base attr_accessible :about, :club, :first_name, :last_name, :profile_picture, :ranking end class player < user end class coach < user end
Comments
Post a Comment