diff options
author | Matthew Robertson <matthewrobertson03@gmail.com> | 2012-12-01 17:56:28 -0800 |
---|---|---|
committer | Matthew Robertson <matthew@cloudclinic.ca> | 2013-02-13 16:01:58 -0800 |
commit | 18ffe50581f41a4f24d791e42826c977276a0df3 (patch) | |
tree | 61c2b013ddf8b5eb22c59e1f5ee9c1c3dfc938fd | |
parent | c0022f8d885d5cca8a7f7d3d64c60af1e04684ea (diff) | |
download | rails-18ffe50581f41a4f24d791e42826c977276a0df3.tar.gz rails-18ffe50581f41a4f24d791e42826c977276a0df3.tar.bz2 rails-18ffe50581f41a4f24d791e42826c977276a0df3.zip |
backport of fix for issue #7630
3 files changed, 23 insertions, 0 deletions
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 99bef61407..7666b8f11f 100644 --- a/activerecord/CHANGELOG.md +++ b/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. diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb index 53d49fef2e..2b9e7ea55d 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -139,6 +139,11 @@ module ActiveRecord 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 diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 40d2e9568d..277a3bddaa 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -346,6 +346,17 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase 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)} |