Pitfall: ActiveRecord callbacks: Method call with multiple conditions

In the following example the method update_offices_people_count won't be called when office_id changes, because it gets overwritten by the second line:

after_save :update_offices_people_count, :if => :office_id_changed? # is overwritten …
after_save :update_offices_people_count, :if => :trashed_changed? # … by this line

Instead write:

after_save :update_offices_people_count, :if => :office_people_count_needs_update?


def office_people_count_needs_update?
  office_id_changed? || trashed_changed?

Or, move the conditions into the callback. This also allows you test the conditions more easily using a unit test:

after_save :update_offices_people_count


def update_offices_people_count
  if office_id_changed? || trashed_changed?  

Also see the card on testing conditional validations.

Martin Straub over 8 years ago
This website uses short-lived cookies to improve usability.
Accept or learn more