Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Counter cache is updated on belongs_to reassignment when not needed

#2786

Reported by Tarmo Tänav · June 10th, 2009 @ 02:30 PM

State: committed
Milestone: 3.x
Assigned to: Michael Koziarski Michael Koziarski
Importance: none

Activity

  1. Tarmo Tänav
  2. Tarmo Tänav
    Tarmo Tänav

    Currently if you reassign a belongs_to association to the same record that it was before and that association has a counter cache the cache is decremented and then again incremented on the same record:

    UPDATE "topics" SET "replies_count" = COALESCE("replies_count", 0) + 1 WHERE ("id" = 12) 
    UPDATE "topics" SET "replies_count" = COALESCE("replies_count", 0) - 1 WHERE ("id" = 12)
    

    That is certainly not useful so the counter cache should only be updated if the record being assigned differs from the one that was present before the assignment.

    Patch against master, but also applies cleanly to 2-3-stable.

    June 10th, 2009 @ 02:34 PM

  3. Tarmo Tänav
    Tarmo Tänav
    • Assigned user set to Michael Koziarski

    June 10th, 2009 @ 03:11 PM

  4. Jeremy Kemper
    Jeremy Kemper
    • Milestone changed from 2.x to 3.x

    May 4th, 2010 @ 06:48 PM

  5. Neeraj Singh
    Neeraj Singh
    • State changed from new to verified
    • Tag set to activerecord, patch, rails3, verified
    • Importance changed from to

    +1

    works fine.

    tests passes in all three adapters.

    July 7th, 2010 @ 05:37 PM

  6. Repository
    Repository
    • State changed from verified to committed

    (from [2ea922bcec333b6484a295b4fee1f4fa75c5704d]) Don't increment and then decrement the same counter when re-assigning a belongs_to association

    [#2786 Counter cache is updated on belongs_to reassignment when not needed state:committed]

    Signed-off-by: Santiago Pastorino santiago@wyeworks.com
    http://github.com/rails/rails/commit/2ea922bcec333b6484a295b4fee1f4...

    July 30th, 2010 @ 02:39 AM