diff options
-rw-r--r-- | activerecord/CHANGELOG | 2 | ||||
-rw-r--r-- | activerecord/lib/active_record/associations/has_many_through_association.rb | 7 | ||||
-rw-r--r-- | activerecord/test/associations/join_model_test.rb | 6 |
3 files changed, 15 insertions, 0 deletions
diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG index 5cb626f91a..4adcfcc4df 100644 --- a/activerecord/CHANGELOG +++ b/activerecord/CHANGELOG @@ -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? 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) diff --git a/activerecord/test/associations/join_model_test.rb b/activerecord/test/associations/join_model_test.rb index a24763b92e..d18c878733 100644 --- a/activerecord/test/associations/join_model_test.rb +++ b/activerecord/test/associations/join_model_test.rb @@ -451,6 +451,12 @@ class AssociationsJoinModelTest < Test::Unit::TestCase 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 |