aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/associations
diff options
context:
space:
mode:
authorRick Olson <technoweenie@gmail.com>2007-09-30 06:47:20 +0000
committerRick Olson <technoweenie@gmail.com>2007-09-30 06:47:20 +0000
commit30a652ad41428b922b1ed637f491776f1f1dff13 (patch)
treee20a92f14f88e6c5c9a46631fb1b744cb6356a3a /activerecord/lib/active_record/associations
parente5a60fb2bfe0c15c297af88c19690788b00109d0 (diff)
downloadrails-30a652ad41428b922b1ed637f491776f1f1dff13.tar.gz
rails-30a652ad41428b922b1ed637f491776f1f1dff13.tar.bz2
rails-30a652ad41428b922b1ed637f491776f1f1dff13.zip
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
Diffstat (limited to 'activerecord/lib/active_record/associations')
-rw-r--r--activerecord/lib/active_record/associations/has_many_through_association.rb12
1 files changed, 11 insertions, 1 deletions
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