In Rails 7.2. the feature ActiveRecord.after_all_transactions_commit
was added, for code that may run either inside or outside a transaction (we have a special card for nested transactions in general) and needs to perform work after the state changes have been properly persisted. e.g. sending an email.
Example:
def publish_article(article)
article.update(published: true)
ActiveRecord.after_all_transactions_commit do
PublishNotificationMailer.with(article: article).deliver_later
end
end
For most use cases there is no action needed at all, since common job interfaces enqueue their jobs after all transactions commit by default e.g. sidekiq Show archive.org snapshot . In the past we used the gem after_transaction_commit Show archive.org snapshot for custom handling, which now can be replaced by the build-in functionality of Rails.
Note: This doesn't solve issues, where you want to have a specific order of after_commit
actions.