rescue_from

So, I was updating a few controllers to trap exceptions using something like:

begin
  @event = Event.find(params[:id]
rescue ActiveRecord::RecordNotFound
  flash[:error] = "Event not found"
  redirect_to :action => :index
end

This worked fine but didn’t seem to be overly “DRY”. Googling a bit, I came across rescue_from and have since replaced all those rescues in my controllers with a single instance of something like:

rescue_from ActiveRecord::RecordNotFound, :with => :invalid_record
 
def invalid_record
  flash[:error] = "Event not found"
  redirect_to :action => :index
end

Nice! I’m starting to see why Rails kicks serious ass. :)

Leave a Reply

You must be logged in to post a comment.