mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Don't unset foreign key when preloading missing record
When a belongs to association's target is set, its foreign key is now updated to match the new target. This is the correct behaviour when a new record is assigned, but not when the existing record is preloaded. As long as we mark the association as loaded, we can skip setting the target when the record is missing and avoid clobbering the foreign key.
This commit is contained in:
parent
ff6d498704
commit
0cdeda5826
2 changed files with 4 additions and 2 deletions
|
@ -42,11 +42,11 @@ module ActiveRecord
|
|||
|
||||
def associate_records_to_owner(owner, records)
|
||||
association = owner.association(reflection.name)
|
||||
association.loaded!
|
||||
if reflection.collection?
|
||||
association.loaded!
|
||||
association.target.concat(records)
|
||||
else
|
||||
association.target = records.first
|
||||
association.target = records.first unless records.empty?
|
||||
end
|
||||
end
|
||||
|
||||
|
|
|
@ -1218,6 +1218,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
|
|||
|
||||
client = assert_queries(2) { Client.preload(:firm).find(c.id) }
|
||||
assert_no_queries { assert_nil client.firm }
|
||||
assert_equal c.client_of, client.client_of
|
||||
end
|
||||
|
||||
def test_preloading_empty_belongs_to_polymorphic
|
||||
|
@ -1225,6 +1226,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
|
|||
|
||||
tagging = assert_queries(2) { Tagging.preload(:taggable).find(t.id) }
|
||||
assert_no_queries { assert_nil tagging.taggable }
|
||||
assert_equal t.taggable_id, tagging.taggable_id
|
||||
end
|
||||
|
||||
def test_preloading_through_empty_belongs_to
|
||||
|
|
Loading…
Reference in a new issue