From 1f8534ca85c32ee26f0e179ac38acf7e61fb0e69 Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Sun, 7 Oct 2018 15:44:05 +0900 Subject: Fix `AssociationRelation` not to set inverse instance key just like before Since #31575, `set_inverse_instance` replaces the foreign key by the current owner immediately to make it happen when a record is added to collection association. But `set_inverse_instance` is not only called when a record is added, but also when a record is loaded from queries. And also, that loaded records are not always associated records for some reason (using `or`, `unscope`, `rewhere`, etc). It is hard to distinguish whether or not we should invoke `set_inverse_instance`, but at least we should avoid the undesired side-effect which was brought from #31575. Fixes #34108. --- .../test/cases/associations/has_many_associations_test.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 036df1c31e..45e2aadaf4 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -2356,6 +2356,18 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal [accounts(:signals37)], firm.accounts.open end + def test_association_with_or_doesnt_set_inverse_instance_key + firm = companies(:first_firm) + accounts = firm.accounts.or(Account.where(firm_id: nil)).order(:id) + assert_equal [firm.id, nil], accounts.map(&:firm_id) + end + + def test_association_with_rewhere_doesnt_inverse_instance_key + firm = companies(:first_firm) + accounts = firm.accounts.rewhere(firm_id: [firm.id, nil]).order(:id) + assert_equal [firm.id, nil], accounts.map(&:firm_id) + end + test "first_or_initialize adds the record to the association" do firm = Firm.create! name: "omg" client = firm.clients_of_firm.first_or_initialize -- cgit v1.2.3