Last time we learn the basics of rails transactions. This time we would take a closer look at the transaction callbacks.

There are two types of callbacks used during transactions.

After commit

after_commit callback is called on every saved or destroyed record after the transaction is committed to the database. Let’s take a look at the example:

class User < ActiveRecord::Base
  after_commit :log_user_activity


  def log_user_activity"User #{id} was updated")

Want to receive useful tips, information about new Ruby gems and articles on a daily basis? Make sure you follow me and say hello!

After rollback

after_rollback callback is called on every saved or destroyed record after the transaction is rolled back. This callback is very useful when you want to log the reason why the transaction failed. You can just log some attributes to check later what was the cause.

class User < ActiveRecord::Base
  after_rollback :log_transaction_status


  def log_transaction_status"User #{id} was not able to perform action")

More control

I mentioned that both callback work on an every saved or destroyed record but you can have more control over after_commit callback. You can decide if you want to trigger given method on an update action, creation or destroy action:

after_commit :log_user_activity, on: :create
after_commit :log_user_activity, on: :update
after_commit :log_user_activity, on: :destroy

You can also use aliases for above calls:

after_create_commit :log_user_activity
after_update_commit :log_user_activity
after_destroy_commit :log_user_activity
Want to become a better Rails developer?
Download for free the Introduction Rails patterns book and dive into the world of refactoring and easy-testable Ruby code today.
Join over 1,000 developers already subscribed to my newsletter and download the book. You can unsubscribe anytime:

Subscribe and get the book!