19 Dec

Rails attribute changed callback

This week, I’d like to show you how to do an action, when an Active Record model’s attribute changes.
In the example, we have a User model, and we want to send an email to the user when the verified attribute changes to true.
As a first step, we need to add an after_save callback to the model:

# app/models/user.rb
class User < ApplicationRecord
  after_save :send_verified_email_if_needed

  def send_verified_email_if_needed
  end
end

In the second step, we will use the ActiveModel::Dirty module of Rails. This module is included by default in all Active Record models, and it provides methods around changes of the attributes. The method we are interested this time is the attribute_changed?(attribute) method. But we will use verified_changed?, which is a shorthand version, to determine when the attribute changed:
# app/models/user.rb
class User < ApplicationRecord
  after_save :send_verified_email_if_needed

  def send_verified_email_if_needed
    if verified_changed? && verified
      UserMailer.with(user: self).confirmed.deliver
    end
  end
end
We also check that the attribute is true and we send the email if the conditions meet.

That’s it for this time.