无法一次又一次找不到没有ID的用户

时间:2014-05-30 08:55:40

标签: ruby-on-rails ruby

大家好,我对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。

2 个答案:

答案 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