From ba687553086fb63965f8b4506a4947b81832b36e Mon Sep 17 00:00:00 2001 From: Subba Rao Pasupuleti Date: Sat, 10 Jul 2010 12:29:09 -0400 Subject: [PATCH] if association is not loaded nested attributes should use in memory record [#5053 state:resolved] --- .../associations/association_collection.rb | 9 ++++++++- activerecord/test/cases/nested_attributes_test.rb | 6 ++++++ 2 files changed, 14 insertions(+), 1 deletions(-) diff --git a/activerecord/lib/active_record/associations/association_collection.rb b/activerecord/lib/active_record/associations/association_collection.rb index 615b7d2..1fc8f33 100644 --- a/activerecord/lib/active_record/associations/association_collection.rb +++ b/activerecord/lib/active_record/associations/association_collection.rb @@ -479,7 +479,14 @@ module ActiveRecord callback(:before_add, record) yield(record) if block_given? @target ||= [] unless loaded? - @target << record unless @reflection.options[:uniq] && @target.include?(record) + index = @target.index(record) + unless @reflection.options[:uniq] && index + if index + @target[index] = record + else + @target << record + end + end callback(:after_add, record) set_inverse_instance(record, @owner) record diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index c9ea0d8..788e1c2 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -811,6 +811,12 @@ class TestHasManyAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveR @part = @ship.parts.create!(:name => "Mast") @trinket = @part.trinkets.create!(:name => "Necklace") end + + test "if association is not loaded and I am saving a child then in memory record should be used" do + @ship.parts_attributes=[{:id => @part.id,:name =>'Deck'}] + assert_equal 1, @ship.parts.proxy_target.size + assert_equal 'Deck', @ship.parts[0].name + end test "when grandchild changed in memory, saving parent should save grandchild" do @trinket.name = "changed" -- 1.7.0.4