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
Tarmo Tänav (committer)
Sun Aug 24 09:41:51 -0700 2008
commit  0048f558e69cfc2675552dd31ea773b2b8271e9b
tree    362a4d17815d20747b5b93fc7498760b09a322bc
parent  2242d3faf12dfc381850e2269016dd4ba95bad86
...
27
28
29
30
31
 
 
 
 
 
32
33
34
...
27
28
29
 
 
30
31
32
33
34
35
36
37
0
@@ -27,8 +27,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
...
391
392
393
 
 
 
 
 
 
 
 
 
 
 
 
394
395
396
...
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
0
@@ -391,6 +391,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