47

What's the preferred way to issue a 404 response from a rails controller action?

John Topley
  • 113,588
  • 46
  • 195
  • 237
readonly
  • 343,444
  • 107
  • 203
  • 205
  • 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 Answers7

39

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
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
Restore the Data Dumps
  • 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
    Use Rails.root.to_s instead of RAILS_ROOT in later versions of rails – deb Jun 15 '12 at 18:35
  • 1
    @deb what difference does it make? String interpolation will call `to_s` implicitly. – Patrick Oscity Jun 25 '14 at 12:32
  • 1
    Ok, [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
38

You can also

raise ActiveRecord::RecordNotFound

exception.

mirza
  • 952
  • 1
  • 9
  • 11
30

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?

Community
  • 1
  • 1
Nickolay Kondratenko
  • 1,871
  • 2
  • 21
  • 25
6

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.

senya
  • 984
  • 12
  • 20
6

Reference:

render :file => '/path/to/some/filenotfound.rhtml', 
                status => 404, :layout => true
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
6

In the ApplicationController define a method like:

def render_404
  render :file => "#{RAILS_ROOT}/public/404.html",  :status => 404
end
huacnlee
  • 430
  • 3
  • 9
0

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.