Skip to content
Browse files

Merge pull request #8400 from matthewrobertson/has-many-through-count…

…er-cache

Fix for has_many_through counter_cache bug

Counter caches were not being updated properly when replacing
has_many_through relationships.
  • Loading branch information...
2 parents 05e9075 + a765c84 commit 0b97ffd45df207ececf139352cbcc8836af89b4c @carlosantoniodasilva carlosantoniodasilva committed Dec 14, 2012
View
5 activerecord/CHANGELOG.md
@@ -1,5 +1,10 @@
## Rails 4.0.0 (unreleased) ##
+* Fix counter cache columns not updated when replacing `has_many :through`
+ associations.
+
+ *Matthew Robertson*
+
* Recognize migrations placed in directories containing numbers and 'rb'.
Fix #8492
View
BIN activerecord/activerecord-4.0.0.beta.gem
Binary file not shown.
View
5 activerecord/lib/active_record/associations/has_many_through_association.rb
@@ -153,6 +153,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
@@ -330,6 +330,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 0b97ffd

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