Skip to content
This repository
Browse code

if association is already loaded and if a find operation is performed…

… on the already loaded association list with an empty hash then do not perform another sql

[#5972 state:resolved]
  • Loading branch information...
commit 7c5c1a07c03ec03536636c26e09b80b29a59beed 1 parent 022519a
Neeraj Singh authored November 14, 2010 tenderlove committed November 15, 2010
3  activerecord/lib/active_record/associations/association_collection.rb
@@ -75,6 +75,7 @@ def first(*args)
75 75
           find(:first, *args)
76 76
         else
77 77
           load_target unless loaded?
  78
+          args = args[1..-1] if args.first.kind_of?(Hash) && args.first.empty?
78 79
           @target.first(*args)
79 80
         end
80 81
       end
@@ -544,7 +545,7 @@ def ensure_owner_is_not_new
544 545
         end
545 546
 
546 547
         def fetch_first_or_last_using_find?(args)
547  
-          args.first.kind_of?(Hash) || !(loaded? || !@owner.persisted? || @reflection.options[:finder_sql] ||
  548
+          (args.first.kind_of?(Hash) && !args.first.empty?) || !(loaded? || !@owner.persisted? || @reflection.options[:finder_sql] ||
548 549
                                          !@target.all? { |record| record.persisted? } || args.first.kind_of?(Integer))
549 550
         end
550 551
 
11  activerecord/test/cases/associations/has_many_associations_test.rb
@@ -66,6 +66,17 @@ def test_create_from_association_should_respect_default_scope
66 66
     assert_equal 'exotic', bulb.name
67 67
   end
68 68
 
  69
+  def test_no_sql_should_be_fired_if_association_already_loaded
  70
+    car = Car.create(:name => 'honda')
  71
+    bulb = car.bulbs.create
  72
+    bulbs = Car.first.bulbs
  73
+    bulbs.inspect # to load all instances of bulbs
  74
+    assert_no_queries do
  75
+      bulbs.first()
  76
+      bulbs.first({})
  77
+    end
  78
+  end
  79
+
69 80
   def test_create_resets_cached_counters
70 81
     person = Person.create!(:first_name => 'tenderlove')
71 82
     post   = Post.first

0 notes on commit 7c5c1a0

Please sign in to comment.
Something went wrong with that request. Please try again.