当用户记录不存在时,如何重定向到404页面? [英] How do I redirect to 404 page when a user record does not exist?

查看:64
本文介绍了当用户记录不存在时,如何重定向到404页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个模型(用户模型).当用户注册帐户时,会发送一封电子邮件以提醒用户他/她的帐户已被激活.在这种情况下,如果管理员删除用户记录,然后用户单击电子邮件中的链接以查看其个人资料,则会显示错误.因此,我想检查用户记录是否存在.如果不存在,则应将用户重定向到404页面.

e.g I have one model (User model). When user signsup for an account, there is an email sent to alert user that his/her account has been activated. In this case, if an admin deletes user record and then user clicks the link from the email to see his or her profile, it will show error. So, I want to check if a user record exists or not. if it does not exist, user should be redirected to 404 page.

我已经尝试了下面的代码,但是没有用.这是我尝试过的以下示例

I have tried the code below but it not working. this is the following example that i have tried

def show
  @user = User.find(params[:id]) or raise ActionController::RoutingError.new('Not Found')
end

那么,对此有解决方案吗?

So, is there a solution for this?

谢谢.

推荐答案

请尝试以下代码:

def show
  @user = User.find_by(id: params[:id])

  raise ActionController::RoutingError.new('Not Found') if @user.blank?
end

这篇关于当用户记录不存在时,如何重定向到404页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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