after_commit_action
after_commit_action copied to clipboard
execute_after_commit triggers unexpected after_commit callbacks
Hey, @magnusvk, I just realised that this code https://github.com/magnusvk/after_commit_action/blob/master/lib/after_commit_action.rb#L23
leads to triggering all after_commit
callbacks on the model that don't have on
option, which might not be an expected behaviour.
Checking all open transaction if they include current record can be slow, not sure what is the best solution here.
maybe not so slow, so one possible solution I see is
def execute_after_commit(&block)
transactions = ActiveRecord::Base.connection.transaction_manager.instance_variable_get(:@stack)
records = transactions.map(&:records).flatten.uniq
if ActiveRecord::Base.connection.open_transactions == 0 || !records.include?(self)
block.call
end
...
end
Hm, well that kind of defeats the purpose, though, right? In that case that code doesn't actually run after commit, it runs right away. The point of adding the record is so that this code can run after the commit. That side effect seems worth it?
I think that is ok. When we call execute_after_commit
we want to execute the code after current record transaction, but if there is no transaction for that record, that means record will not change and then there is no purpose of waiting some other transactions, we can execute the block straight away.
I don't think that's always true. What if I specifically warp a block in a transaction, for example? I'd expect after_commit hooks to run after the completion of that block, wouldn't I?