From 18cb0a7b1ddb937f7775b0b8c13ac78cd5c59eb5 Mon Sep 17 00:00:00 2001 From: George Ogata Date: Thu, 26 Nov 2009 00:05:57 -0500 Subject: [PATCH] Set inverse for #replace on a has_one association. --- .../associations/has_one_association.rb | 1 + .../associations/inverse_associations_test.rb | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 0 deletions(-) diff --git a/activerecord/lib/active_record/associations/has_one_association.rb b/activerecord/lib/active_record/associations/has_one_association.rb index b85a40b..081d623 100644 --- a/activerecord/lib/active_record/associations/has_one_association.rb +++ b/activerecord/lib/active_record/associations/has_one_association.rb @@ -57,6 +57,7 @@ module ActiveRecord @target = (AssociationProxy === obj ? obj.target : obj) end + set_inverse_instance(obj, @owner) @loaded = true unless @owner.new_record? or obj.nil? or dont_save diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb index 47f83db..ee360df 100644 --- a/activerecord/test/cases/associations/inverse_associations_test.rb +++ b/activerecord/test/cases/associations/inverse_associations_test.rb @@ -135,6 +135,21 @@ class InverseHasOneTests < ActiveRecord::TestCase assert_equal m.name, f.man.name, "Name of man should be the same after changes to newly-created-child-owned instance" end + def test_parent_instance_should_be_shared_with_replaced_child + man = Man.find(:first) + old_face = man.face + new_face = Face.new + + assert_not_nil man.face + man.face.replace(new_face) + + assert_equal man.name, new_face.man.name, "Name of man should be the same before changes to parent instance" + man.name = 'Bongo' + assert_equal man.name, new_face.man.name, "Name of man should be the same after changes to parent instance" + new_face.man.name = 'Mungo' + assert_equal man.name, new_face.man.name, "Name of man should be the same after changes to replaced-parent-owned instance" + end + def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Man.find(:first).dirty_face } end -- 1.6.4.2