Search code examples
ruby-on-railsrubyhttphttp-status-code-404

How to redirect to a 404 in Rails?


I'd like to 'fake' a 404 page in Rails. In PHP, I would just send a header with the error code as such:

header("HTTP/1.0 404 Not Found");

How is that done with Rails?


Solution

  • Don't render 404 yourself, there's no reason to; Rails has this functionality built in already. If you want to show a 404 page, create a render_404 method (or not_found as I called it) in ApplicationController like this:

    def not_found
      raise ActionController::RoutingError.new('Not Found')
    end
    

    Rails also handles AbstractController::ActionNotFound, and ActiveRecord::RecordNotFound the same way.

    This does two things better:

    1) It uses Rails' built in rescue_from handler to render the 404 page, and 2) it interrupts the execution of your code, letting you do nice things like:

      user = User.find_by_email(params[:email]) or not_found
      user.do_something!
    

    without having to write ugly conditional statements.

    As a bonus, it's also super easy to handle in tests. For example, in an rspec integration test:

    # 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)
    

    And minitest:

    assert_raises(ActionController::RoutingError) do 
      get '/something/you/want/to/404'
    end
    

    OR refer more info from Rails render 404 not found from a controller action