Get more information from ActiveRecord :: RecordNotFound in Rails

I handle the RecordNotFound error in my application_controller.rb as follows:

  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 receive additional information, such as the name of the class / table whose record was not found. How can I do it?

Thanks.

+4
source share
4 answers

Say for example

 begin @user = User.find(params[:id]) rescue ActiveRecord::RecordNotFound flash[:notice] = "#No such record in User for id :: {params[:id]} on #{action_name}" end 

UPDATE

 flash[:notice] = t('flash.recordnotfound',:class_name => self.class.name, :column_name => params[:id], :action_name => action_name) 

Now in your config/locales/en.yml (this will help translate, refer to i18n here )

 flash: recordnotfound: "Sorry, no record od %{column_name} in class %{class_name} was found on you action %{action_name}" 

If you do not want to use locales, just enter this information in flash[:notice] .

More dynamic?

Write a function and use the same flash [: notice]. It will not hurt at all.

Want more data?

This is a quick fix, I always <%= params%> in my views to easily find out what is happening and what will happen. Then you can open the rail console and play along with various actions, etc.

 user = User.new user.save user.errors.messages 

All this is pretty good data, I think.

Good luck.

+2
source

You can define a parameter in your crash handler and an exception will be thrown there.

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

If you cannot get this information from the exception, you're out of luck (I think).

+3
source

I had success:

 # 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 

NTN

EDIT: Space error removed at the end of Regex. Thanks to the commentators. :)

+2
source

Once you create an instance of the model, you can check something like.

 human = Human.new human.errors 

Check it out in the rails console so you can play with it and use it in the main controller.

 rescue_from ActiveRecord::RecordNotFound do |exception| raise ActiveRecord, exception.message, exception.backtrace end 

EDIT Verify that the application controller is expanding the database.

 class ApplicationController < ActionController::Base rescue_from Exception, :with => :record_not_found private def record_not_found(e) flash[:error] = "Oops, we cannot find this record" + e.message redirect_to :back end end 
0
source

Source: https://habr.com/ru/post/1390562/


All Articles