Read more

Rendering a custom 404 page in Rails 2

Dominik Schöler
September 02, 2011Software engineer at makandra GmbH

Simple: Tell the application controller how to handle exceptions, here a RecordNotFound error.
Do this with the following line:

# application_controller.rb

  rescue_from ActiveRecord::RecordNotFound, :with => :render_404
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

This will call the method render_404 whenever a RecordNotFound error occurs (you could pass a lambda instead of a symbol, too).
Now write this method:

def render_404
  render 'errors/404', :status => '404'
end

Finally create a 404 document views/errors/errors.html.haml.

%h1 Record Not Found

.error The record you requested could not be retrieved in my database.

Any 404 error that is caused by something not found in your Rails app will render a nice message using your default layout. Similarly, you may catch and handle any other error.

Posted by Dominik Schöler to makandra dev (2011-09-02 16:59)