Skip to content

Commit 0f9de98

Browse files
authored
Merge pull request rails#54533 from dkani/main
Add details of per transaction callbacks and `after_all_transactions_commit` [ci skip]
2 parents 7a031e3 + 5bdeace commit 0f9de98

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

guides/source/active_record_callbacks.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1337,6 +1337,45 @@ NOTE: This applies to all `after_*_commit` variations too, such as
13371337
[`after_update_commit`]:
13381338
https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#method-i-after_update_commit
13391339

1340+
### Per transaction callback
1341+
1342+
You can also register transactional callbacks such as `before_commit`, `after_commit` and `after_rollback` on a specific transaction.
1343+
This is handy in situations where you need to perform an action that isn't specific to a model but rather a unit of work.
1344+
1345+
`ActiveRecord::Base.transaction` yields an `ActiveRecord::Transaction` object, which allows registering the said callbacks on it.
1346+
1347+
```ruby
1348+
Article.transaction do |transaction|
1349+
article.update(published: true)
1350+
1351+
transaction.after_commit do
1352+
PublishNotificationMailer.with(article: article).deliver_later
1353+
end
1354+
end
1355+
```
1356+
1357+
### `ActiveRecord.after_all_transactions_commit`
1358+
1359+
[`ActiveRecord.after_all_transactions_commit`][] is a callback that allows you to run code after all the current transactions have been successfully committed to the database.
1360+
1361+
```ruby
1362+
def publish_article(article)
1363+
Article.transaction do
1364+
Post.transaction do
1365+
ActiveRecord.after_all_transactions_commit do
1366+
PublishNotificationMailer.with(article: article).deliver_later
1367+
# An email will be sent after the outermost transaction is committed.
1368+
end
1369+
end
1370+
end
1371+
end
1372+
```
1373+
1374+
A callback registered to `after_all_transactions_commit` will be triggered after the outermost transaction is committed. If any of the currently open transactions is rolled back, the block is never called.
1375+
In the event that there are no open transactions at the time a callback is registered, the block will be yielded immediately.
1376+
1377+
[`ActiveRecord.after_all_transactions_commit`]: https://api.rubyonrails.org/classes/ActiveRecord.html#method-c-after_all_transactions_commit
1378+
13401379
Callback Objects
13411380
----------------
13421381

0 commit comments

Comments
 (0)