Permalink
Browse files

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
  • Loading branch information...
1 parent b49fcde commit d51e7f8252269492a511a9eb41f2832646a44248 @technoweenie technoweenie committed Jul 25, 2007
View
@@ -1,5 +1,7 @@
*SVN*
+# Ensure that has_many :through associations use a count query instead of loading the target when #size is called. Closes #8800 [lifo]
+
* Added :unless clause to validations #8003 [monki]. Example:
def using_open_id?
@@ -96,6 +96,13 @@ def create!(attrs = nil)
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)
@@ -451,6 +451,12 @@ def test_create_associate_when_adding_to_has_many_through
assert_nothing_raised { vertices(:vertex_1).sinks << vertices(:vertex_5) }
end
+ def test_has_many_through_collection_size_doesnt_load_target_if_not_loaded
+ author = authors(:david)
+ assert_equal 9, author.comments.size
+ assert !author.comments.loaded?
+ end
+
def test_adding_junk_to_has_many_through_should_raise_type_mismatch
assert_raise(ActiveRecord::AssociationTypeMismatch) { posts(:thinking).tags << "Uhh what now?" }
end

0 comments on commit d51e7f8

Please sign in to comment.