如何重定向到 Rails 中的 404? [英] How to redirect to a 404 in Rails?
问题描述
我想在 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 页面,请在 ApplicationController
中创建一个 render_404
方法(或我称之为 not_found
),如下所示:
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.
这在两件事上做得更好:
This does two things better:
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)
和最小测试:
assert_raises(ActionController::RoutingError) do
get '/something/you/want/to/404'
end
或从 中参考更多信息从控制器操作中找不到 Rails 渲染 404
这篇关于如何重定向到 Rails 中的 404?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!