ruby-on-rails ruby on rails中的“undefined method `session_token' for nil:NilClass”

laik7k3q  于 2023-08-08  发布在  Ruby
关注(0)|答案(1)|浏览(124)

我一直在用Ruby on Rails开发一些Web应用程序,然后当我转到:localhost:3000I get this error:

undefined method `session_token' for nil:NilClass

if (user_id = session[:user_id])
       user = User.find_by(id: user_id)             
       @current_user ||= user if session[:session_token] == user.session_token

字符串
红色标记在这条线上:

@current_user ||= user if session[:session_token] == user.session_token


completel current_user方法如下:

def current_user
        if (user_id = session[:user_id])
            user = User.find_by(id: user_id)            
            @current_user ||= user if session[:session_token] == user.session_token         
        elsif (user_id = cookies.encrypted[:user_id])
            user = User.find_by(id: user_id)
            if user&.authenticated?(:remember, cookies[:remember_token])
                log_in user
                @current_user = user
            end
        end
    end

5jvtdoz2

5jvtdoz21#

find_by更改为find_by!

if (user_id = session[:user_id])
       user = User.find_by!(id: user_id)             
       @current_user ||= user if session[:session_token] == user.session_token

字符串

相关问题