diff options
author | Yves Senn <yves.senn@gmail.com> | 2013-11-11 09:32:18 -0800 |
---|---|---|
committer | Yves Senn <yves.senn@gmail.com> | 2013-11-11 09:32:18 -0800 |
commit | 1a80133392490fead222c98bbdbdf4e189812e43 (patch) | |
tree | 5876bd466300396612893a17e6746f9cabf049cc | |
parent | b31b6e669935cfa7e88e75c02dbd0892d1b9853e (diff) | |
parent | dbb7ee1bfd16d9aabd3b3ed1a566c8752e9af3c0 (diff) | |
download | rails-1a80133392490fead222c98bbdbdf4e189812e43.tar.gz rails-1a80133392490fead222c98bbdbdf4e189812e43.tar.bz2 rails-1a80133392490fead222c98bbdbdf4e189812e43.zip |
Merge pull request #12748 from dm1try/fix_counter_cache_for_through_association
Fixes #11079, prevent the counter cache from being decremented twice when destroying a record on a has_many :through association
3 files changed, 17 insertions, 1 deletions
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 54c243951d..524a048c7c 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,10 @@ +* Prevent the counter cache from being decremented twice when destroying + a record on a has_many :through association. + + Fixes #11079. + + *Dmitry Dedov* + * Unify boolean type casting for `MysqlAdapter` and `Mysql2Adapter`. `type_cast` will return `1` for `true` and `0` for `false`. 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 56331bbb0b..31b8d27892 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -163,7 +163,7 @@ module ActiveRecord delete_through_records(records) - if source_reflection.options[:counter_cache] + if source_reflection.options[:counter_cache] && method != :destroy counter = source_reflection.counter_cache_column klass.decrement_counter counter, records.map(&:id) 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 c450b1beb5..47592f312e 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -514,6 +514,15 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase assert_equal(post.taggings.count, post.taggings_count) end + def test_update_counter_caches_on_destroy + post = posts(:welcome) + tag = post.tags.create!(name: 'doomed') + + assert_difference 'post.reload.taggings_count', -1 do + tag.tagged_posts.destroy(post) + end + end + def test_replace_association assert_queries(4){posts(:welcome);people(:david);people(:michael); posts(:welcome).people(true)} |