我试图在他们登录后显示当前用户名。
因此,在页面顶部会显示“以 Patrick 身份登录”。但是,我设置了一个多态关联,每个注册的用户要么是球员,要么是教练。
当教练和球员都打网球时,多态关联位于标签或 :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