How to send a mailer when specific model attribute is updated

630 views Asked by At

I have an app that has an articles model. Users can follow an article to receive emails whenever that article is edited.

Currently, emails get sent for every picayune change to every attribute of the model. I would like to either specify that a mailer gets sent only when specific attributes are changed, or include in the email a list of the attributes that were changed in the latest update.

I am using paper_trail to track versions of articles s.t. a new version is created only when the major attributes get changed. That would seem to be a convenient peg for a callback. i.e. when a new version is created, the update gets sent. But I am not sure whether I need to manually create a Papertrail model or do something else.

Separately, to create the list of changed attributes, I think I can use the changed.keys method to return the list of attributes that were changed, but only before the instance is saved. I assumed I could do something like:

def update
      @article = Article.friendly.find(params[:id])
      @changes = @article.changed
      if @article.update_attributes(article_params)

...

but how do I pass @changes to the mailer?

Any ideas appreciated!

1

There are 1 answers

1
Prashant4224 On

You can call the after_update callback method

models/article.rb

after_update :send_email

def send_email
  UserMailer.email_notification(self.user).deliver
end