Active Record Ruby on Rails

Ruby on Rails / Transactions – callbacks

Ruby on Rails / Transactions – callbacks January 30, 20181 Comment

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

Do you want to read about given topic?

Hit me on twitter or use contact form and let me know

Download free RSpec & TDD ebook

Do you want to earn more or jump to the next level in your company? Do you know that testing skills are one of the most desired skills? There is only first step: start testing and do it right. My ebook can help you. Subscribe to the newsletter to get a free copy of the book.

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *