Rails attribute changed callback

19 Dec 2023

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 attibute changes. The method we need this time is attribute_changed?(attribute). 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.

Hire me for a penetration test

Let's find the security holes before the bad guys do.

Did you enjoy reading this? Sign up to the Rails Tricks newsletter for more content like this!

Or follow me on Twitter

Related posts