且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Rails中重定向到404?

更新时间:2022-04-29 03:22:17

不要自己渲染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