Skip to content

Commit 6d7235d

Browse files
committed
Fix clearing the inverse relation when has_many_inversing is enabled
rails#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)`.
1 parent 7373b58 commit 6d7235d

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

activerecord/lib/active_record/associations/collection_association.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,8 @@ def target=(record)
276276
return super unless reflection.klass.has_many_inversing
277277

278278
case record
279+
when nil
280+
# It's not possible to remove the record from the inverse association.
279281
when Array
280282
super
281283
else

activerecord/test/cases/associations/belongs_to_associations_test.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1205,6 +1205,20 @@ def test_reassigning_the_parent_id_updates_the_object
12051205
assert_equal companies(:another_firm), client.firm_with_condition
12061206
end
12071207

1208+
def test_assigning_nil_on_an_association_clears_the_associations_inverse
1209+
with_has_many_inversing do
1210+
book = Book.create!
1211+
citation = book.citations.create!
1212+
1213+
assert_same book, citation.book
1214+
1215+
assert_nothing_raised do
1216+
citation.book = nil
1217+
citation.save!
1218+
end
1219+
end
1220+
end
1221+
12081222
def test_clearing_an_association_clears_the_associations_inverse
12091223
author = Author.create(name: "Jimmy Tolkien")
12101224
post = author.create_post(title: "The silly medallion", body: "")

0 commit comments

Comments
 (0)