What's the preferred way to issue a 404 response from a rails controller action?
-
possible duplicate of [How to redirect to a 404 in Rails?](http://stackoverflow.com/questions/2385799/how-to-redirect-to-a-404-in-rails) – Oliver Matthews Apr 14 '14 at 09:41
7 Answers
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

- 30,799
- 15
- 56
- 79

- 38,967
- 12
- 96
- 122
-
6[This answer](http://stackoverflow.com/questions/2385799/how-to-redirect-to-a-404-in-rails#answer-4983354) on another question strikes me as more powerful. Bonus: it includes test code :-) – webmat Jan 31 '12 at 20:16
-
2
-
1@deb what difference does it make? String interpolation will call `to_s` implicitly. – Patrick Oscity Jun 25 '14 at 12:32
-
1Ok, [Erwin Bolwidt](http://stackoverflow.com/users/981744/erwin-bolwidt) rollback [my edit](http://stackoverflow.com/revisions/779837/3) even when it [approved](http://stackoverflow.com/review/suggested-edits/5248553). So you need to add `, :layout => false` after `:status => 404` to exclude all other layout. – Artem P Jul 09 '14 at 08:15
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?

- 1
- 1

- 1,871
- 2
- 21
- 25
-
2Same but simpler: `raise ActionController::RoutingError, 'Not Found'` – Dave Burt Jun 15 '15 at 00:26
In Rails 5 you can use
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 404
with 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.

- 984
- 12
- 20
render :file => '/path/to/some/filenotfound.rhtml',
status => 404, :layout => true

- 524,688
- 99
- 697
- 795
In the ApplicationController define a method like:
def render_404
render :file => "#{RAILS_ROOT}/public/404.html", :status => 404
end

- 430
- 3
- 9
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.

- 3
- 3