作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我想在 Rails 中“伪造”一个 404 页面。在 PHP 中,我只发送一个包含错误代码的 header :
header("HTTP/1.0 404 Not Found");
Rails 是如何做到的?
最佳答案
不要自己渲染 404,没有理由这样做; Rails 已经内置了这个功能。如果要显示 404 页面,请在 ApplicationController
中创建一个 render_404
方法(或我称之为 not_found
),如下所示:
def not_found
raise ActionController::RoutingError.new('Not Found')
end
Rails 还以相同的方式处理 AbstractController::ActionNotFound
和 ActiveRecord::RecordNotFound
。
这有两个好处:
1) 它使用 Rails 内置的 rescue_from
处理程序来呈现 404 页面,并且2) 它会中断你的代码的执行,让你做一些好的事情,比如:
user = User.find_by_email(params[:email]) or not_found
user.do_something!
无需编写难看的条件语句。
作为奖励,它在测试中也非常容易处理。例如,在 rspec 集成测试中:
# 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 render 404 not found from a controller action 的更多信息
关于ruby-on-rails - 如何重定向到 Rails 中的 404?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2385799/
我是一名优秀的程序员,十分优秀!