From 6d7235dd20df3e1a1402caa73ae04a1dd0891824 Mon Sep 17 00:00:00 2001 From: Jean Boussier Date: Thu, 8 Jul 2021 10:43:48 +0200 Subject: [PATCH] Fix clearing the inverse relation when has_many_inversing is enabled https://github.com/rails/rails/pull/42601 fixed clearing the inverse relation, but it didn't account for collection associations. For these, just assigning `nil` isn't possible because we need the record to remove it from the collection. So this PR introduce an explicit method for this purpose rather than reuse `inversed_from(nil)`. --- .../associations/collection_association.rb | 2 ++ .../associations/belongs_to_associations_test.rb | 14 ++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index c56b118129246..9ae36ecce3444 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -276,6 +276,8 @@ def target=(record) return super unless reflection.klass.has_many_inversing case record + when nil + # It's not possible to remove the record from the inverse association. when Array super else diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index b94e93a124f8f..53a1ed654c36a 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -1205,6 +1205,20 @@ def test_reassigning_the_parent_id_updates_the_object assert_equal companies(:another_firm), client.firm_with_condition end + def test_assigning_nil_on_an_association_clears_the_associations_inverse + with_has_many_inversing do + book = Book.create! + citation = book.citations.create! + + assert_same book, citation.book + + assert_nothing_raised do + citation.book = nil + citation.save! + end + end + end + def test_clearing_an_association_clears_the_associations_inverse author = Author.create(name: "Jimmy Tolkien") post = author.create_post(title: "The silly medallion", body: "")