Today I Learned

hashrocket A Hashrocket project

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

ActiveRecord::Base.transaction do
  Fruit.create(name: 'Banana')
  Fruit.create(name: 'Kiwi')
  Fruit.create(name: 'Rasberry')

Now, the callback is called (for all 3 times) only when the final Fruit creation for a Rasberry succeeds.

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.