Couldn't find User with id=1

荒凉一梦 提交于 2019-12-21 02:36:24

问题


I've a current_user method to handle authentication.

application_controller.rb

protect_from_forgery
helper_method :current_user

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

but when I try to acces a to a page I get the following error:

Couldn't find User with id=1
app/controllers/application_controller.rb:10:in `current_user'

How can I pass @current_user a sort of default value so if there's no user it will redirect to login page.

Thanks for helping.


回答1:


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.



来源:https://stackoverflow.com/questions/8526082/couldnt-find-user-with-id-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!