General rescue throughout controller when id not found - RoR

weltschmerz picture weltschmerz · Nov 17, 2012 · Viewed 7.8k times · Source

I have stumbled upon a situation where my application looks for an id that does not exist in the database. An exception is thrown. Of course, this is a pretty standard situation for any web developer.

Thanks to this answer I know that using rescue deals with the situation pretty neatly, like so:

def show
  @customer = Customer.find(params[:id])
  rescue ActiveRecord::RecordNotFound #customer with that id cannot be found
    redirect_to action: :index        #redirect to index page takes place instead of crashing
end

In case the customer cannot be found, the user gets redirected to the index page. This works absolutely fine.

Now, this is all nice, but I need to do the same rescue attempts in actions like show, edit, destroy, etc, i.e. every controller method that needs a specific id.

Having said that, here's my question: Isn't there any way to generally tell my controller that if it can't find the id in any of its methods, it shall redirect to the index page (or, generally, perform a specific task)?

Answer

Baldrick picture Baldrick · Nov 17, 2012

You must use rescue_from for this task. See example in the Action Controller Overview Guide

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found

  private

  def record_not_found
    redirect_to action: :index
  end
end