aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/associations/has_many_through_association.rb
diff options
context:
space:
mode:
authorRick Olson <technoweenie@gmail.com>2007-07-25 03:09:21 +0000
committerRick Olson <technoweenie@gmail.com>2007-07-25 03:09:21 +0000
commitd51e7f8252269492a511a9eb41f2832646a44248 (patch)
tree49854337d0b4b414171eb1ef63f8718169b211ff /activerecord/lib/active_record/associations/has_many_through_association.rb
parentb49fcde7e50c8eb378e7b1ae08f65c70f6de20e4 (diff)
downloadrails-d51e7f8252269492a511a9eb41f2832646a44248.tar.gz
rails-d51e7f8252269492a511a9eb41f2832646a44248.tar.bz2
rails-d51e7f8252269492a511a9eb41f2832646a44248.zip
Ensure that has_many :through associations use a count query instead of loading the target when #size is called. Closes #8800 [lifo]
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@7237 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
Diffstat (limited to 'activerecord/lib/active_record/associations/has_many_through_association.rb')
-rw-r--r--activerecord/lib/active_record/associations/has_many_through_association.rb7
1 files changed, 7 insertions, 0 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 ebe1be04e5..ec093548da 100644
--- a/activerecord/lib/active_record/associations/has_many_through_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_through_association.rb
@@ -96,6 +96,13 @@ module ActiveRecord
end
end
+ # Returns the size of the collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and
+ # 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
+ end
+
# Calculate sum using SQL, not Enumerable
def sum(*args, &block)
calculate(:sum, *args, &block)