diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 06c16537da918accf58123fe5159c617a491671a..b6f9bf5fef5b693725f8b5f23558d9cae7294548 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,9 @@ +* Prevent `build_association` from `touching` a parent record if the record isn't persisted for `has_one` associations. + + Fixes #38219 + + *Josh Brody* + * Add support for `if_not_exists` option for adding index. The `add_index` method respects `if_not_exists` option. If it is set to true diff --git a/activerecord/lib/active_record/associations/has_one_association.rb b/activerecord/lib/active_record/associations/has_one_association.rb index 99971286a3f32036bc789cfa0ae24c4c6ade3c9b..2a961995da12463c30e100da30bf32e1a3ea9fbb 100644 --- a/activerecord/lib/active_record/associations/has_one_association.rb +++ b/activerecord/lib/active_record/associations/has_one_association.rb @@ -81,7 +81,9 @@ def remove_target!(method) target.delete when :destroy target.destroyed_by_association = reflection - target.destroy + if target.persisted? + target.destroy + end else nullify_owner_attributes(target) remove_inverse_instance(target) diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index 40746f76cb82b07be2e82dd3cb1c1c6ca09c0afc..f9cbfebe0efefbd87beb170d5754f1b10caff66e 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -851,4 +851,22 @@ def test_dependency_should_halt_parent_destruction assert_not author.destroy end end + + class SpecialCar < ActiveRecord::Base + self.table_name = "cars" + has_one :special_bulb, inverse_of: :car, dependent: :destroy, class_name: "SpecialBulb", foreign_key: "car_id" + end + + class SpecialBulb < ActiveRecord::Base + self.table_name = "bulbs" + belongs_to :car, inverse_of: :special_bulb, touch: true, class_name: "SpecialCar" + end + + def test_has_one_with_touch_option_on_nonpersisted_built_associations_doesnt_update_parent + car = SpecialCar.create(name: "honda") + assert_queries(1) do + car.build_special_bulb + car.build_special_bulb + end + end end