This project is archived and is in readonly mode.

#2824 ✓resolved
Alex Tomlins

[Patch] has_many :through doesn't update counter_cache on join model correctly.

Reported by Alex Tomlins | June 22nd, 2009 @ 05:09 PM | in 3.x

If you have a counter_cache on a join model used in a has_many :through association, when removing items from the association, the counter_cache doesn't get decremented correctly. e.g.

class Post < ActiveRecord::Base
  has_many :taggings
  has_many :tags, :through => :taggings
end

class Tagging < ActiveRecord::Base
  belongs_to :post, :counter_cache => true
  belongs_to :tag
end

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :posts, :through => :taggings
end

post = Post.create!()
tag1 = Tag.create!()
tag2 = Tag.create!()
post.tags << tag1
post.reload.taggings_count # => 1
post.tags = [tag2]
post.reload.taggings_count # => 2 !  Should be 1

This happens because #delete_records in HasManyThroughAssociation does a delete_all. The attached patch changes this to a destroy_all which fixes the issue.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Shared Ticket Bins

Referenced by

Pages