Couldn't find User with id=1

前端 未结 1 548
星月不相逢
星月不相逢 2021-02-10 22:39

I\'ve a current_user method to handle authentication.

application_controller.rb

protect_from_forgery
helper_method :current         


        
相关标签:
1条回答
  • 2021-02-10 23:25

    It looks like your session contains old data, specifically an id (1) of a user which no longer exists. Try handling the RecordNotFound exception raised by ActiveRecord, and returning nil:

    def current_user
        @current_user ||= User.find(session[:user_id]) if session[:user_id]
        rescue ActiveRecord::RecordNotFound
    end  
    

    To redirect, you should add a second before_filter which checks for a user and handles redirecting to the login path:

    before_filter :require_user
    
    def require_user
      redirect_to login_path unless current_user
    end
    

    Remember to omit require_user for your login action by adding skip_before_filter :require_login to whichever controller manages your authentication.

    0 讨论(0)
提交回复
热议问题