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
I run an indie startup providing vulnerability scanning for your Ruby on Rails app.
It is free to use at the moment, and I am grateful for any feedback about it.If you would like to give it a spin, you can do it here: Vulnerability Scanning for your Ruby on Rails app!