This blog is part of our Rails 5 series.
Rails 4.x has
after_commit
callback. after_commit is called after a record has been created, updated or
destroyed.
class User < ActiveRecord::Base
after_commit :send_welcome_mail, on: create
after_commit :send_profile_update_notification, on: update
after_commit :remove_profile_data, on: destroy
def send_welcome_mail
EmailSender.send_welcome_mail(email: email)
end
end
Rails 5 had added following three aliases.
- after_create_commit
- after_update_commit
- after_destroy_commit
Here is revised code after using these aliases.
class User < ApplicationRecord
after_create_commit :send_welcome_mail
after_update_commit :send_profile_update_notification
after_destroy_commit :remove_profile_data
def send_welcome_mail
EmailSender.send_welcome_mail(email: email)
end
end
We earlier stated that after_commit callback is executed at the end of
transaction. Using after_commit with a transaction block can be tricky. Please
checkout our earlier post about
Gotcha with after_commit callback in Rails
.

Written byHitesh Rawal
Related blogs
- 01Rails 5 Active Record attributes APIDecember 11, 2018 · Abhay Nikam
- 02Rails 5 Create module and class level variablesSeptember 5, 2016 · Abhishek Jain
- 03Rails 5 silences assets logs in dev mode by defaultSeptember 2, 2016 · Midhun Krishna
- 04Rails 5 disables autoloading while app in productionAugust 29, 2016 · Shailesh Kalamkar