aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGodfrey Chan <godfreykfc@gmail.com>2014-07-15 08:34:44 -0700
committerGodfrey Chan <godfreykfc@gmail.com>2014-07-15 08:34:44 -0700
commit473b09f6160a4663ded59d529d47be219eb18d9a (patch)
tree38346d96baf098597a2b7e7b75dff931c21ece00
parentebb95018a71631a964774a594a087591c75f181e (diff)
parent63fd88ca5c255a84b61ce81c41dfe9928ea101d9 (diff)
downloadrails-473b09f6160a4663ded59d529d47be219eb18d9a.tar.gz
rails-473b09f6160a4663ded59d529d47be219eb18d9a.tar.bz2
rails-473b09f6160a4663ded59d529d47be219eb18d9a.zip
Merge pull request #15266 from dv/use_counter_cache_for_empty_call
If a counter_cache exists, use it for #empty?
-rw-r--r--activerecord/lib/active_record/associations/has_many_association.rb8
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb7
2 files changed, 15 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb
index 453615ba87..2a97d0ed31 100644
--- a/activerecord/lib/active_record/associations/has_many_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_association.rb
@@ -41,6 +41,14 @@ module ActiveRecord
end
end
+ def empty?
+ if has_cached_counter?
+ size.zero?
+ else
+ super
+ end
+ end
+
private
# Returns the number of records in this collection.
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index 3e5b7e655b..fe961e871c 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -837,6 +837,13 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
end
+ def test_calling_empty_with_counter_cache
+ post = posts(:welcome)
+ assert_queries(0) do
+ assert_not post.comments.empty?
+ end
+ end
+
def test_custom_named_counter_cache
topic = topics(:first)