public
Description: Ruby on Rails
Homepage: http://rubyonrails.org
Clone URL: git://github.com/rails/rails.git
Fix has_many#count_records. [#865 state:resolved]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
fxn (author)
Thu Aug 21 07:45:06 -0700 2008
lifo (committer)
Thu Aug 21 07:48:04 -0700 2008
commit  a970f916fb1e05376733e2d42d9bcc2b873af355
tree    32341e068add430be9687f38dc08722820d45845
parent  ea40f71431a821b2ddb37be6ea3ee7d8dac63b85
...
35
36
37
38
39
 
 
 
 
 
40
41
42
...
35
36
37
 
 
38
39
40
41
42
43
44
45
0
@@ -35,8 +35,11 @@ module ActiveRecord
0
           else
0
             @reflection.klass.count(:conditions => @counter_sql, :include => @reflection.options[:include])
0
           end
0
-          
0
-          @target = [] and loaded if count == 0
0
+
0
+          # If there's nothing in the database and @target has no new records
0
+          # we are certain the current target is an empty array. This is a
0
+          # documented side-effect of the method that may avoid an extra SELECT.
0
+          @target ||= [] and loaded if count == 0
0
           
0
           if @reflection.options[:limit]
0
             count = [ @reflection.options[:limit], count ].min
...
395
396
397
 
 
 
 
 
 
 
 
 
 
 
 
398
399
400
...
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
0
@@ -395,6 +395,18 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
0
     assert_equal 3, company.clients_of_firm.size
0
   end
0
 
0
+  def test_collection_size_twice_for_regressions
0
+    post = posts(:thinking)
0
+    assert_equal 0, post.readers.size
0
+    # This test needs a post that has no readers, we assert it to ensure it holds,
0
+    # but need to reload the post because the very call to #size hides the bug.
0
+    post.reload
0
+    post.readers.build
0
+    size1 = post.readers.size
0
+    size2 = post.readers.size
0
+    assert_equal size1, size2
0
+  end
0
+
0
   def test_build_many
0
     company = companies(:first_firm)
0
     new_clients = assert_no_queries { company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) }

Comments