Active Record transaction callbacks

15 Apr 2024

Active Record introduced transaction callbacks recently. This change allows you to have a callback for the whole transaction, rather than to just have callbacks on a record’s after_commit event. To make this possible, ActiveRecord::Base.transaction yields a transaction object now and the callback can be registered on that:

Order.transaction do |transaction|
  Order.pending.each do |order|
    order.process!
  end

  transaction.after_commit do
    AdminMailer.orders_processed.deliver_later
  end
end

In the above example the notification to the admin will only happen if the transaction is committed. We could also hook into the after_rollback callback:

Order.transaction do |transaction|
  Order.pending.each do |order|
    order.process!
  end

  transaction.after_commit do
    AdminMailer.orders_processed.deliver_later
  end

  transaction.after_rollback do
    AdminMailer.orders_processing_failed.deliver_later
  end
end

Hire me for a penetration test

Let's find the security holes before the bad guys do.

Or follow me on Twitter

Related posts