gpt4 book ai didi

ruby-on-rails - 如何重定向到 Rails 中的 404?

转载 作者:数据小太阳 更新时间:2023-10-29 06:16:09 25 4
gpt4 key购买 nike

我想在 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::ActionNotFoundActiveRecord::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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com