Search code examples
ruby-on-railsurl-routing

Rails: How can I display a page on a certain status code?


I'm relatively new to Rails, and I still don't know a lot about routing. How would I display a certain view (such as 404.html.erb) when the user gets a certain error code (404)? For example, if a user GETs a page that doesn't exist (404), how can I listen for that and display a certain page on that event?

I know that a Rails app comes with a public folder and pre-generated 404, 500, and 422 error code .html pages, but they don't seem to work for me. When I go to a page that doesn't exist, I receive a GET error. How would I change this?

Thanks!


Solution

  • You can setup custom routes to render dynamic pages from your controller just as normal controller-view templates.

    config/routes.rb

    MyApp::Application.routes.draw do
      # custom error routes
      match '/404' => 'errors#not_found', :via => :all
      match '/500' => 'errors#internal_error', :via => :all
    end
    

    app/controllers/errors_controller.rb

    class ErrorsController < ApplicationController    
      def not_found
        render(:status => 404)
      end
    end
    

    app/views/errors/not_found.html.erb

    <div class="container">
      <div class="align-center">
        <h3>Page not found</h3>
        <%= link_to "Go to homepage", root_path %>
      </div>
    </div>