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.
Did you enjoy reading this? Sign up to the Rails Tricks newsletter for more content like this!
Or follow me on Twitter
I run an indie startup providing vulnerability scanning for your Ruby on Rails app.
It is free to use at the moment, and I am grateful for any feedback about it.If you would like to give it a spin, you can do it here: Vulnerability Scanning for your Ruby on Rails app!