Skip to content
Browse files

Merge pull request #9278 from matthewrobertson/backport-hmt-counter-c…

…ache-bug

Backport of #8400 to fix for issue #7630, a bug in has_many :through counter caches.
  • Loading branch information...
2 parents c0022f8 + 18ffe50 commit d1904aff6f04bcca0ee3da4aae8477f2f30b7e85 @carlosantoniodasilva carlosantoniodasilva committed
View
7 activerecord/CHANGELOG.md
@@ -1,3 +1,10 @@
+* Fix counter cache columns not updated when replacing `has_many :through`
+ associations.
+ Backport #8400.
+ Fix #7630.
+
+ *Matthew Robertson*
+
* Don't update `column_defaults` when calling destructive methods on column with default value.
Backport c517602.
Fix #6115.
View
5 activerecord/lib/active_record/associations/has_many_through_association.rb
@@ -139,6 +139,11 @@ def delete_records(records, method)
delete_through_records(records)
+ if source_reflection.options[:counter_cache]
+ counter = source_reflection.counter_cache_column
+ klass.decrement_counter counter, records.map(&:id)
+ end
+
if through_reflection.macro == :has_many && update_through_counter?(method)
update_counter(-count, through_reflection)
end
View
11 activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -346,6 +346,17 @@ def test_update_counter_caches_on_delete_with_dependent_nullify
end
end
+ def test_update_counter_caches_on_replace_association
+ post = posts(:welcome)
+ tag = post.tags.create!(:name => 'doomed')
+ tag.tagged_posts << posts(:thinking)
+
+ tag.tagged_posts = []
+ post.reload
+
+ assert_equal(post.taggings.count, post.taggings_count)
+ end
+
def test_replace_association
assert_queries(4){posts(:welcome);people(:david);people(:michael); posts(:welcome).people(true)}

0 comments on commit d1904af

Please sign in to comment.
Something went wrong with that request. Please try again.