Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Know what event triggered the after_commit of an 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 to know what event triggered the after commit here?

Please don't tell me to have 2 after commits like:

after_commit :do_something_on_update, on: :update
after_commit :do_something_on_create, on: :create
like image 841
Wazery Avatar asked May 08 '16 13:05

Wazery


1 Answers

ActiveRecord uses 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 multiple actions. If both :create and :update are possible in the same transaction in your program you need two ifs, not an if/else.

like image 153
Dave Schweisguth Avatar answered Oct 06 '22 17:10

Dave Schweisguth