after_commit_everywhere icon indicating copy to clipboard operation
after_commit_everywhere copied to clipboard

calling methods that trigger callbacks can cause `after_commit` callbacks to run multiple times

Open DeedleFake opened this issue 2 years ago • 1 comments

If an after_commit is called inside of a transaction and that transaction has calls to model methods that can trigger model callbacks, the block passed to after_commit will be called multiple times. For example,

ActiveRecord::Base.transaction do
  User.create!(email:)
  ev = Event.create!(name: 'created user', source: 'admin')

  after_commit do
    send_welcome_email!
  end

  track_event!(ev)
end

When this transaction runs, the welcome e-mail will be sent multiple times because the block is run repeatedly.

DeedleFake avatar Nov 07 '23 18:11 DeedleFake

That's weird, but it is hard to understand how to replicate such a behavior.

Can you please create a reproduction example of your use case, e.g. using ActiveRecord's executable test case template?

Envek avatar Dec 01 '23 01:12 Envek