Handling 404s when RecordNotFound, UnknownAction and RoutingError

When handling 404s, you want to display the 404 page and return HTTP status 404 when a particular record is not found, the action requested is unknown or if there is a routing error.

Add the following to your application_controller.rb file, towards the end:

class ApplicationController < ActionController::Base
...

  rescue_from ActiveRecord::RecordNotFound, :with => :rescue_action_in_public

  private

  # handles 404 when a record is not found.
  def rescue_action_in_public(exception)
    case exception
    when ActiveRecord::RecordNotFound, ActionController::UnknownAction, ActionController::RoutingError
      render :file => "#{RAILS_ROOT}/public/404.html", :layout => 'layouts/application', :status => 404
    else
      super
    end
  end
end
VN:F [1.9.17_1161]
Rating: 3.0/5 (2 votes cast)
VN:F [1.9.17_1161]
Rating: +1 (from 1 vote)
Handling 404s when RecordNotFound, UnknownAction and RoutingError, 3.0 out of 5 based on 2 ratings

Leave a Reply