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.
1class User < ActiveRecord::Base 2 after_commit :send_welcome_mail, on: create 3 after_commit :send_profile_update_notification, on: update 4 after_commit :remove_profile_data, on: destroy 5 6 def send_welcome_mail 7 EmailSender.send_welcome_mail(email: email) 8 end 9end
Rails 5 added new aliases
Rails 5 had added following three aliases.
- after_create_commit
- after_update_commit
- after_destroy_commit
Here is revised code after using these aliases.
1class User < ApplicationRecord 2 after_create_commit :send_welcome_mail 3 after_update_commit :send_profile_update_notification 4 after_destroy_commit :remove_profile_data 5 6 def send_welcome_mail 7 EmailSender.send_welcome_mail(email: email) 8 end 9end
Note
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 .