Rails: check if the model was really saved in after_save

The ActiveRecord function is used to call the after_save callback each time the save method is called, even if the model has not been changed and no insert / update request has been created.

This is the default behavior. And this is normal in most cases.

But some of the after_save callbacks are sensitive if the model was actually saved or not.

Is there a way to determine if the model was really saved in after_save?

I run the following test code:

class Stage < ActiveRecord::Base after_save do pp changes end end s = Stage.first s.name = "q1" s.save! 
+4
source share
2 answers

Using ActiveRecord to call the after_save callback every time the save method even if the model has not been changed and there is no insert / update request generated.

ActiveRecord performs: after_save callbacks each time a record is successfully saved regardless of its change.

 # record invalid, after_save not triggered Record.new.save # record valid, after_save triggered r = Record.new(:attr => value) # record valid and not changed, after_save triggered r.save 

What you want to know is changing the record, not saving the record. Can you easily accomplish this using record.changed?

 class Record after_save :do_something_if_changed protected def do_something_if_changed if changed? # ... end end end 
+6
source

After saving, check if the saved object is a new object

 a = ModelName.new a.id = 1 a.save a.new_record? #=> false 
+3
source

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


All Articles