May 11, 2016
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.
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
.
If this blog was helpful, check out our full blog archive.