Jake Worth

ActiveRecord After Commit Callback

Published: October 05, 2015 2 min read

  • ruby

Today I used a pretty awesome Rails callback, after_commit.

after_commit executes after a database transaction completes, making it ideal for third-party integrations. Social media and chat applications come to mind.

Here is an example:

after_commit :notify_twitter, on: [:create, :update], unless: -> { draft? || tweeted }

Human version: post to twitter whenever a thing is created or updated (or touched via the touch method), unless it’s a draft or it’s already been tweeted. Don’t post on destroy.

I like the granular control of this callback, and think it’s better in this case than after_save because it covers several more situations. If it fails, that needs to be handled independently from the transaction.


✉️ Get better at programming by learning with me. Subscribe to Jake Worth's Newsletter for bi-weekly ideas, creations, and curated resources from across the world of programming. Join me today!

Blog of Jake Worth, software engineer in Maine.

© 2022 Jake Worth.