Ruby-on-rails 您如何从 rails 控制器操作发出 404 响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/779784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you issue a 404 response from a rails controller action?
提问by Readonly
What's the preferred way to issue a 404 response from a rails controller action?
从 rails 控制器操作发出 404 响应的首选方法是什么?
采纳答案by Jason Punyon
This seems good...
这似乎不错...
# Rails 2 and below
render :file => "#{RAILS_ROOT}/public/404.html", :status => 404
# Rails 3 and up
render :file => "#{Rails.root}/public/404.html", :status => 404
回答by mirza
You can also
你也可以
raise ActiveRecord::RecordNotFound
raise ActiveRecord::RecordNotFound
exception.
例外。
回答by Nickolay Kondratenko
The following way was the best for me:
以下方式对我来说是最好的:
raise ActionController::RoutingError.new('Not Found')
or just
要不就
raise ActionController::RoutingError, 'Not Found'
Or there are some other solutions: How to redirect to a 404 in Rails?
或者还有其他一些解决方案: How to redirect to a 404 in Rails?
回答by tvanfosson
回答by huacnlee
In the ApplicationController define a method like:
在 ApplicationController 中定义一个方法,如:
def render_404
render :file => "#{RAILS_ROOT}/public/404.html", :status => 404
end
回答by senya
In Rails 5 you can use
在 Rails 5 中,您可以使用
head 404
This will set the response code of your action to 404. If you immediately return after this from your action method, your action will respond 404with no actual body. This may be useful when you're developing API endpoints, but with end user HTTP requests you'll likely prefer some visible body to inform the user about the error.
这会将您的操作的响应代码设置为404. 如果您在此之后立即从您的 action 方法返回,您的 action 将404没有实际的 body响应。这在您开发 API 端点时可能很有用,但对于最终用户的 HTTP 请求,您可能更喜欢一些可见的正文来通知用户错误。
回答by camzillajs101
If you wanted to issue a status code on a redirect (e.g. 302), you could put this in routes.rb:get "/somewhere", to: redirect("/somewhere_else", status: 302).
However, this would only work for redirection, not straight up loading a page.
如果您想在重定向时发出状态代码(例如 302),您可以将其放在routes.rb: 中get "/somewhere", to: redirect("/somewhere_else", status: 302)。
但是,这仅适用于重定向,不能直接加载页面。

