大家好,我对RoR有些问题。我尝试定义像这样的当前用户
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def current_user
@current_user ||= User.find(session[:user_id])
end
end
这是我的错误:无法找到没有ID的用户
我不知道为什么......我的BBD中有一个user_id。
答案 0 :(得分:1)
您收到此错误,因为您的会话中没有:user_id。尝试:
@current_user ||= session[:user_id] && User.find(session[:user_id])
或
@current_user ||= User.find_by(id: session[:user_id])
但请注意,如果没有密钥,每次调用current_user
时,rails都会尝试从数据库中获取用户(因为@current_user
为nil)。避免它的最佳方法是:
def current_user
return @current_user if defined?(@current_user)
@current_user = User.find(session[:user_id])
end
这样你也可以缓存nil结果。
答案 1 :(得分:0)
解决方案是
def current_user
@current_user ||= session[:user_id] && User.find(session[:user_id])
en
OR
def current_user
return unless session[:user_id]
@current_user ||= User.find(session[:user_id])
end