after_commit callback in active_record
We use ActiveRecord callbacks at times to sync data between systems but if you're using transactions you don't want to have called a callback like after_create and then have the whole transaction roll back, then you'd have out of sync systems! Rails conveniently includes an after_commit hook for such a case.
class Fruit < ActiveRecord::Base after_commit :sync_to_fruitstand end ActiveRecord::Base.transaction do Fruit.create(name: 'Banana') Fruit.create(name: 'Kiwi') Fruit.create(name: 'Rasberry') end
Now, the callback is called (for all 3 times) only when the final Fruit creation for a Rasberry succeeds.Tweet