rails/rails — pull request #9737 by wangjohn (2013-03-15 18:41:38+00:00)
Title: The counter cache will now work correctly when the primary key is changed. Fixes #9722.

Currently, defining an association with a counter cache means that the counter only increments or decrements when an object is created or destroyed (see example in #9722). However, if an object updates its primary key and removes itself from an association, the counter cache will not update correctly.

I've included a ``before_save`` callback that increments or decrements the counter if the primary key gets changed in a ``belongs_to`` association. If the primary key was present before but is no longer present after the update, then the counter gets decremented. Likewise, if the primary key was not present before but is present after the update, then the counter gets incremented.

The counter cache only gets changed if the record is not new (so it doesn't conflict with the ``after_create`` callback currently in place.