Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get extra information from ActiveRecord::RecordNotFound in Rails

I handle RecordNotFound error in my application_controller.rb as follow:

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

  private 

   def record_not_found
     flash[:error] = "Oops, we cannot find this record"
     redirect_to :back
   end

But I would like to get more information, such as class/table name of which record was not found. How should I go about it?

Thank you.

like image 643
AdamNYC Avatar asked Feb 21 '23 21:02

AdamNYC


2 Answers

I had some success with this:

# in app/controllers/application_controller.rb

rescue_from ActiveRecord::RecordNotFound, with: :record_not_found

def record_not_found exception
  result = exception.message.match /Couldn't find ([\w]+) with 'id'=([\d]+)/
  # result[1] gives the name of the model
  # result[2] gives the primary key ID of the object that was not found
end

HTH

EDIT: Whitespace error removed at the end of the Regex. Thanks to the commenters. :)

like image 94
Dan Laffan Avatar answered May 05 '23 14:05

Dan Laffan


You can define a parameter in your rescue handler and exception will be passed there.

def record_not_found exception
  flash[:error] = "Oops, we cannot find this record"
  # extract info from exception

  redirect_to :back
end

If you can't get that info from the exception, you're out of luck (I think).

like image 42
Sergio Tulentsev Avatar answered May 05 '23 13:05

Sergio Tulentsev