From 30a652ad41428b922b1ed637f491776f1f1dff13 Mon Sep 17 00:00:00 2001 From: Rick Olson Date: Sun, 30 Sep 2007 06:47:20 +0000 Subject: Make size for has_many :through use counter cache if it exists. Closes #9734 [xaviershay] git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@7692 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- .../associations/has_many_through_association.rb | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'activerecord/lib') 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 de0d7cc8a9..62839c4637 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -100,7 +100,9 @@ module ActiveRecord # calling collection.size if it has. If it's more likely than not that the collection does have a size larger than zero # and you need to fetch that collection afterwards, it'll take one less SELECT query if you use length. def size - loaded? ? @target.size : count + return @owner.send(:read_attribute, cached_counter_attribute_name) if has_cached_counter? + return @target.size if loaded? + return count end # Calculate sum using SQL, not Enumerable @@ -258,6 +260,14 @@ module ActiveRecord end alias_method :sql_conditions, :conditions + + def has_cached_counter? + @owner.attribute_present?(cached_counter_attribute_name) + end + + def cached_counter_attribute_name + "#{@reflection.name}_count" + end end end end -- cgit v1.2.3