I am working on a functionality where i need to trigger a mail to a list of users once the record field value has been updated successfully.
For eg: I have a Blog model which has published attribute(represents a column in my database table) with default value as false. When the user published the blog, the field value will become true and i need to send some mails.
- Which is the best way of doing it?
- If I can use after_update callback, how will i get to know that published column has been updated during the last update call?
- Is there a way to access the old value of the published attribute after the update?
Any help is highly appreciated…
Best Answer
1) might be a little subjective but I'll answer that along with 2) ActiveRecord provides methods to indicate whether an attribute has changed. You can use the attribute name +
_changed?
. E.g. If your model has aname
attribute, then it will also respond to#name_changed?
Here is one way you can send email only if an attribute has been changed:3) The old attribute value can be accessed by appending
_was
. E.g.#name_was
will return the old value of the name field.UPDATE:
To send an email only the first time that a field is switched from false to true you will need to add another field to your database, such as
email_sent
. Since the condition for thesend_email
callback became more complex, I moved it into the callback itself. After the email is sent, set theemail_sent
field to true, so that no further emails are delivered.