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.22_1171]
Rating: 4.3/5 (6 votes cast)
VN:F [1.9.22_1171]
Rating: +3 (from 3 votes)
Handling 404s when RecordNotFound, UnknownAction and RoutingError, 4.3 out of 5 based on 6 ratings
Facebook Twitter Email

Leave a Reply