Multiple after_update callbacks with attribute change conditions are triggering only the first one

2.4k Views Asked by At

Multiple after_update callbacks with attribute change conditions are triggering only the first one.

class Article < ActiveRecord::Base
  after_update :method_1, :if => proc{ |obj| obj.status_changed? && obj.status == 'PUBLISHED' }
  after_update :method_2, :if => proc{ |obj| obj.status_changed? && obj.status == 'PUBLISHED' && obj.name == 'TEST' }
  ...
end

method_1 is triggered when a model object is updated:

Article.last.update_attributes(status: 'PUBLISHED', name: 'TEST')

While method_2 is not triggered.

2

There are 2 best solutions below

0
sa77 On BEST ANSWER

You can just use one callback with an if...end block to filter operations you want to perform in each cases.

class Article < ActiveRecord::Base
  after_update :method_1, :if => proc{ |obj| obj.status_changed? && obj.status == 'PUBLISHED' }
  ...

  def method_1        
    if self.name == 'TEST'
      # stuff you want to do on method_2
    else
      # stuff you want to do on method_1
    end
  end
end
0
gkats On

Make sure you check the return values of your callbacks. If a before_* or after_* ActiveRecord callback returns false, all later callbacks in the chain are cancelled.

From the docs (see Canceling callbacks)

If a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled.