[英]How do you issue a 404 response from a rails controller action?
从rails控制器动作发出404响应的首选方法是什么?
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
You can also 你也可以
raise ActiveRecord::RecordNotFound
exception. 例外。
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? 或者还有其他一些解决方案: 如何在Rails中重定向到404?
In the ApplicationController define a method like: 在ApplicationController中定义一个方法,如:
def render_404
render :file => "#{RAILS_ROOT}/public/404.html", :status => 404
end
In Rails 5 you can use 在Rails 5中,您可以使用
head 404
This will set the response code of your action to 404
. 这会将您的操作的响应代码设置为404
。 If you immediately return after this from your action method, your action will respond 404
with no actual body. 如果您在行动方法之后立即返回,您的行动将回复404
而没有实际的身体。 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. 这在您开发API端点时可能很有用,但对于最终用户HTTP请求,您可能更喜欢某些可见的主体来通知用户该错误。
If you wanted to issue a status code on a redirect (eg 302), you could put this in routes.rb
: 如果要在重定向上发出状态代码(例如302),可以将其放在routes.rb
:
get "/somewhere", to: redirect("/somewhere_else", status: 302)
. get "/somewhere", to: redirect("/somewhere_else", status: 302)
。
However, this would only work for redirection, not straight up loading a page. 但是,这只适用于重定向,而不是直接加载页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.