Know what event triggered the after_commit ActiveRecord model

I have the following snippet:

class Product after_commit :do_something, on: %i(update create) def do_something if # update ... else # create ... end end end 

How do I know which event triggered a transaction after being committed here?

Please do not tell me that I have 2 after commits:

 after_commit :do_something_on_update, on: :update after_commit :do_something_on_create, on: :create 
+7
ruby ruby-on-rails activerecord ruby-on-rails-4 rails-activerecord
source share
2 answers

How to simply check previous id values ​​if it is nil , it means we do create

 def do_something id_changes = self.previous_changes[:id] # Creating if id_changes && id_changes.first.nil? ... else # Updating ... end end 
+3
source share

ActiveRecord using transaction_include_any_action? :

 def do_something if transaction_include_any_action?([:create]) # handle create end if transaction_include_any_action?([:update]) # handle update end end 

A transaction can include several actions. If both :create and :update possible in one transaction in your program, you need two if , not if / else .

+3
source share

All Articles