在 Michael Hartls rails 教程中,我遇到了以下代码:
module SessionsHelper
def current_user=(user)
@current_user = user
end
def current_user #get logged in user
@current_user||=User.find_by_remember_token(:remember_token)
end
def sign_in(user) #sign the user in by setting cookies
cookies.permanent[:remember_token]= user.remember_token
current_user = user
end
def signed_in?(user) #check whether user signed in
!current_user.nil?
end
end
我的 SessionsController 创建操作如下所示:
def create
user = User.find_by_email(params[:session][:email])
if user && user.authenticate(params[:session][:password])
sign_in user # sign the user in by setting cookies
else
flash.now[:error]= "Invalid email/password"
render 'new'
end
end
为什么我们需要一个 writer 方法
def current_user=(用户)在 SessionsHelper 模块中?
我们不能直接将 user 的值分配给 @current_user 变量吗
登入方法 ?可以这样做吗:
module SessionsHelper
# Notice that there is no def current_user=(user) method.
def current_user
@current_user||=User.find_by_remember_token(:remember_token)
end
def sign_in(user)
cookies.permanent[:remember_token]= user.remember_token
@current_user = user #set the current user directly withoout a writer method
end
def signed_in?(user)
!current_user.nil?
end
end