Skip to content

Commit 5562abb

Browse files
committed
Dont try to load the record from the db if preloading didn't find anything
1 parent 607f945 commit 5562abb

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

activerecord/lib/active_record/association_preload.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,11 @@ def set_association_single_records(id_to_record_map, reflection_name, associated
159159
association_proxy.__send__(:set_inverse_instance, associated_record, mapped_record)
160160
end
161161
end
162+
163+
id_to_record_map.each do |id, records|
164+
next if seen_keys.include?(id.to_s)
165+
records.each {|record| record.send("set_#{reflection_name}_target", nil) }
166+
end
162167
end
163168

164169
# Given a collection of ActiveRecord objects, constructs a Hash which maps

activerecord/test/cases/associations/eager_test.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -833,4 +833,10 @@ def test_include_has_one_using_primary_key
833833
end
834834
end
835835

836+
def test_preloading_empty_polymorphic_parent
837+
t = Tagging.create!(:taggable_type => 'Post', :taggable_id => Post.maximum(:id) + 1, :tag => tags(:general))
838+
839+
assert_queries(2) { @tagging = Tagging.preload(:taggable).find(t.id) }
840+
assert_no_queries { assert ! @tagging.taggable }
841+
end
836842
end

0 commit comments

Comments
 (0)