From 45d4d141f971e50e2df40bbf3559ee254ebc81b9 Mon Sep 17 00:00:00 2001 From: heruku Date: Sun, 24 Nov 2013 03:47:17 -0600 Subject: [PATCH] changed update counter to act on unscoped model --- activerecord/CHANGELOG.md | 6 ++++++ activerecord/lib/active_record/counter_cache.rb | 2 +- .../test/cases/associations/has_many_associations_test.rb | 8 ++++++++ activerecord/test/models/topic.rb | 4 ++++ 4 files changed, 19 insertions(+), 1 deletion(-) diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index fc40bd88be..1e035c11e0 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,9 @@ +* Update counter cache on a has_many relationship regardless of default scope + + Fix #12952. + + *Uku Taht* + * `rename_index` adds the new index before removing the old one. This allows to rename indexes on columns with a foreign key and prevents the following error: diff --git a/activerecord/lib/active_record/counter_cache.rb b/activerecord/lib/active_record/counter_cache.rb index 3aa5faed87..7e3bef9431 100644 --- a/activerecord/lib/active_record/counter_cache.rb +++ b/activerecord/lib/active_record/counter_cache.rb @@ -77,7 +77,7 @@ module ActiveRecord "#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{value.abs}" end - where(primary_key => id).update_all updates.join(', ') + unscoped.where(primary_key => id).update_all updates.join(', ') end # Increment a numeric field by one, via a direct SQL update. diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 45bc974025..bfb80afa61 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -1781,4 +1781,12 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal [original_child], car.reload.failed_bulbs end + + test 'updates counter cache when default scope is given' do + topic = DefaultRejectedTopic.create approved: true + + assert_difference "topic.reload.replies_count", 1 do + topic.approved_replies.create! + end + end end diff --git a/activerecord/test/models/topic.rb b/activerecord/test/models/topic.rb index 40c8e97fc2..f81ffe1d90 100644 --- a/activerecord/test/models/topic.rb +++ b/activerecord/test/models/topic.rb @@ -106,6 +106,10 @@ class ImportantTopic < Topic serialize :important, Hash end +class DefaultRejectedTopic < Topic + default_scope -> { where(approved: false) } +end + class BlankTopic < Topic # declared here to make sure that dynamic finder with a bang can find a model that responds to `blank?` def blank?