Posted about 9 years ago. Visible to the public. Repeats.

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:

Copy
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:

Copy
after_save :update_offices_people_count, :if => :office_people_count_needs_update? private def office_people_count_needs_update? office_id_changed? || trashed_changed? end

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

Copy
after_save :update_offices_people_count private def update_offices_people_count if office_id_changed? || trashed_changed? ... end end

Also see the card on testing conditional validations.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Avatar
Martin Straub
Last edit:
almost 4 years ago
by Daniel Straßner
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Martin Straub to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more