diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index c56b118129..9ae36ecce3 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -276,6 +276,8 @@ module ActiveRecord 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 b94e93a124..53a1ed654c 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 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase 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: "")