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

查看:40
本文介绍了如何在 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 页面,请在 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::ActionNotFoundActiveRecord::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)

还有最小化:

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

或参考 的更多信息Rails 渲染 404 未从控制器操作中找到

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

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