Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - ActiveRecord - Trigger mail on change of a field value

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.

  1. Which is the best way of doing it?
  2. If I can use after_update callback, how will i get to know that published column has been updated during the last update call?
  3. Is there a way to access the old value of the published attribute after the update?

Any help is highly appreciated...

like image 341
nkm Avatar asked Oct 11 '11 17:10

nkm


1 Answers

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 a name attribute, then it will also respond to #name_changed? Here is one way you can send email only if an attribute has been changed:

class MyModel
  after_update :send_email, :if => :column_name_changed?

  def send_email
    # Send email here
  end
end

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 the send_email callback became more complex, I moved it into the callback itself. After the email is sent, set the email_sent field to true, so that no further emails are delivered.

class MyModel
  after_update :send_email

  def send_email
    if column_name_changed? && !email_sent?
      # Send email here
      update_attribute :email_sent, true
    end
  end
end
like image 66
Wizard of Ogz Avatar answered Oct 23 '22 17:10

Wizard of Ogz