Trigger email send when a rails model boolean field is set to true instead of false
-
10-02-2021 - |
Question
I have two models in my application. Families has_many Individuals's. individuals's belongs_to Families.
I'm trying to make it so that when a boolean field in the Families model is set to "true" an email is sent to all of the email addresses stored against Individuals when the family is "updated".
Can anyone help with this? I've been able to get ActiveMailer sending an email when an Individual is created easily enough, but cannot find a way to trigger on the update of a specific field?
Any help would be greatly appreciated!
Solution
Maybe you could use an after filter?
on the Family model
after_update :email_individuals
private
def email_individuals
if boolean_field_changed?
individuals.each do |i|
// send out emails here
end
end
end
The next step would be to move this out of the request cycle and into a queue.
Hope I grokked your question properly.
OTHER TIPS
Toby has the right idea but I disagree that this should be implemented in the controller... this is much better suited to a model after_update callback. something like this:
def update_fired
if yourfield_changed?
#send mail here
end
end
Then just make sure in your model you set the method to be the after_update callback
Easiest way would be to add something to the update action of your controller
if individual.boolean_field_changed? and individual.boolean_field
individuals.each do |ind|
Mailer.deliver_mail(ind)
end
end
Rails has an API for detecting changes in model fields (in the above case you add _changed? to the field name and it will tell you if the field has been changed.