Skip to content
This repository
Browse code

Fix preloading of belongs_to with null foreign key generating useless…

… query [#1027 state:resolved]
  • Loading branch information...
commit 707d0dd3e1e8df7771073670e4257d933d2818f9 1 parent 428e77b
Frederick Cheung authored December 17, 2008 lifo committed December 18, 2008
1  activerecord/lib/active_record/association_preload.rb
@@ -307,6 +307,7 @@ def preload_belongs_to_association(records, reflection, preload_options={})
307 307
 
308 308
         klasses_and_ids.each do |klass_and_id|
309 309
           klass_name, id_map = *klass_and_id
  310
+          next if id_map.empty?
310 311
           klass = klass_name.constantize
311 312
 
312 313
           table_name = klass.quoted_table_name
3  activerecord/test/cases/associations/eager_test.rb
@@ -145,7 +145,7 @@ def test_finding_with_includes_on_belongs_to_association_with_same_include_inclu
145 145
   def test_finding_with_includes_on_null_belongs_to_association_with_same_include_includes_only_once
146 146
     post = posts(:welcome)
147 147
     post.update_attributes!(:author => nil)
148  
-    post = assert_queries(2) { Post.find(post.id, :include => {:author_with_address => :author_address}) } # find the post, then find the author which is null so no query for the address
  148
+    post = assert_queries(1) { Post.find(post.id, :include => {:author_with_address => :author_address}) } # find the post, then find the author which is null so no query for the author or address
149 149
     assert_no_queries do
150 150
       assert_equal nil, post.author_with_address
151 151
     end
@@ -705,4 +705,5 @@ def test_conditions_on_join_table_with_include_and_limit
705 705
   def test_order_on_join_table_with_include_and_limit
706 706
     assert_equal 5, Developer.find(:all, :include => 'projects', :order => 'developers_projects.joined_on DESC', :limit => 5).size
707 707
   end
  708
+
708 709
 end

0 notes on commit 707d0dd

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