In Rails 7.2, they introduce Article.current_transaction.after_commit, saying “for code that may run either inside or outside a transaction and needs to perform work after the state changes have been properly persisted”, and they give the following code:
def publish_article(article)
article.update(published: true)
ActiveRecord.after_all_transactions_commit do
PublishNotificationMailer.with(article: article).deliver_later
end
end
My question is, isn’t anything you do after the article.update(published: true)
line only going to run after the transaction was committed anyway? Wouldn’t it raise a Rollback exception if it wasn’t committed? So what does wrapping PublishNotificationMailer.with(article: article).deliver_later
inside a ActiveRecord.after_all_transactions_commit
block even accomplish here? Why wouldn’t you just have the code be:
def publish_article(article)
article.update(published: true)
PublishNotificationMailer.with(article: article).deliver_later
end