如何在Rails中重定向到404? [英] How to redirect to a 404 in Rails?

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

问题描述

我想在Rails中伪造一个404页面。在PHP中,我只会发送带有错误代码的标头:

I'd like to 'fake' a 404 page in Rails. In PHP, I would just send a header with the error code as such:

header("HTTP/1.0 404 Not Found");

如何用Rails完成?

How is that done with Rails?

推荐答案

不要自己渲染404,没有理由; Rails已经内置了这个功能。如果要显示404页面,请在<$中创建一个 render_404 方法(或者我调用的 not_found ) c $ c> ApplicationController 像这样:

Don't render 404 yourself, there's no reason to; Rails has this functionality built in already. If you want to show a 404 page, create a render_404 method (or not_found as I called it) in ApplicationController like this:

def not_found
  raise ActionController::RoutingError.new('Not Found')
end

Rails还处理 AbstractController :: ActionNotFound ActiveRecord :: RecordNotFound 以同样的方式。

Rails also handles AbstractController::ActionNotFound, and ActiveRecord::RecordNotFound the same way.

这样可以做得更好:

1)它使用Rails内置的 rescue_from 处理程序来渲染404页面,和
2)它会中断你的代码的执行,让你做一些好的事情,比如:

1) It uses Rails' built in rescue_from handler to render the 404 page, and 2) it interrupts the execution of your code, letting you do nice things like:

  user = User.find_by_email(params[:email]) or not_found
  user.do_something!

,无需编写丑陋的条件语句。

without having to write ugly conditional statements.

作为奖励,它在测试中也非常容易处理。例如,在rspec集成测试中:

As a bonus, it's also super easy to handle in tests. For example, in an rspec integration test:

# RSpec 1

lambda {
  visit '/something/you/want/to/404'
}.should raise_error(ActionController::RoutingError)

# RSpec 2+

expect {
  get '/something/you/want/to/404'
}.to raise_error(ActionController::RoutingError)

和minitest:

assert_raises(ActionController::RoutingError) do 
  get '/something/you/want/to/404'
end

这篇关于如何在Rails中重定向到404?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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