找不到ID为1的用户 [英] Couldn't find User with id=1

查看:70
本文介绍了找不到ID为1的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个current_user方法来处理身份验证.

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'

如何为@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.

感谢您的帮助.

推荐答案

您的会话似乎包含旧数据,特别是不再存在的用户的id(1).尝试处理ActiveRecord引发的RecordNotFound异常,并返回nil:

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  

要重定向,您应该添加第二个before_filter来检查用户并处理重定向到登录路径:

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

请记住,通过将skip_before_filter :require_login添加到管理您的身份验证的任何控制器,来省略require_user的登录操作.

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

这篇关于找不到ID为1的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆