Rails transactions – callbacks

Ruby on Rails / Active Record

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
    Rails.logger.info("User #{id} was updated")
  end
end

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
    Rails.logger.info("User #{id} was not able to perform action")
  end
end

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