Active Record transaction callbacks

15 Apr 2024
Security For Rails Developers

Develop the right mindset for Rails security

Avoid shipping vulnerable code by learning how to prevent security issues in your Rails applications.

Get the course for $99

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

Or follow me on Twitter

Related posts