Develop the right mindset for Rails security
Avoid shipping vulnerable code by learning how to prevent security issues in your Rails applications.
Get the course for $99This 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.