From 0cdeda5826fc7cf26de404dcdd6d747531a32b6c Mon Sep 17 00:00:00 2001 From: Eugene Kenny Date: Sat, 24 Mar 2018 22:18:05 +0000 Subject: 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. --- activerecord/lib/active_record/associations/preloader/association.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb index 0f38d6bbda..d6f7359055 100644 --- a/activerecord/lib/active_record/associations/preloader/association.rb +++ b/activerecord/lib/active_record/associations/preloader/association.rb @@ -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 -- cgit v1.2.3