From d80a47dc766eb0058785f2223d092e22b8dc3b87 Mon Sep 17 00:00:00 2001 From: Alex McHale Date: Wed, 26 Jan 2011 16:08:00 -0600 Subject: [PATCH] If a new record receives an existing record as its accepts_nested_attributes_for, it should use the existing object instead of failing. --- .../lib/active_record/nested_attributes.rb | 9 +++++++++ activerecord/test/cases/nested_attributes_test.rb | 6 ++++++ 2 files changed, 15 insertions(+), 0 deletions(-) diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb index 16023de..bc55832 100644 --- a/activerecord/lib/active_record/nested_attributes.rb +++ b/activerecord/lib/active_record/nested_attributes.rb @@ -323,6 +323,15 @@ module ActiveRecord options = self.nested_attributes_options[association_name] attributes = attributes.with_indifferent_access + if attributes['id'].present? + record = send(association_name) + if !record || record.id.to_s != attributes['id'].to_s + reflection = self.class.reflect_on_association(association_name) + record = reflection.klass.find_by_id(attributes['id']) + send("#{association_name}=", record) if record + end + end + if (options[:update_only] || !attributes['id'].blank?) && (record = send(association_name)) && (options[:update_only] || record.id.to_s == attributes['id'].to_s) assign_to_or_mark_for_destruction(record, attributes, options[:allow_destroy]) unless call_reject_if(association_name, attributes) diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index e1f938b..fe7ef85 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -499,6 +499,12 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase Ship.accepts_nested_attributes_for :update_only_pirate, :update_only => true, :allow_destroy => false end + + def test_should_use_an_existing_reference_on_a_new_record + @pirate = Pirate.create!(:catchphrase => 'Aye') + @ship = Ship.new(:name => 'The Black Angus Beef', :pirate_attributes => { :id => @pirate.id }) + assert_equal @ship.pirate.catchphrase, 'Aye' + end end module NestedAttributesOnACollectionAssociationTests -- 1.7.3.1