From 08302d2febb7374c64eaa1b7b87b898b59468402 Mon Sep 17 00:00:00 2001 From: James Le Cuirot Date: Sat, 12 Jun 2010 11:51:49 +0100 Subject: [PATCH] When not overwriting unsaved updates in nested attributes, allow already-saved records to be refreshed. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- .../associations/association_collection.rb | 6 +++++- activerecord/test/cases/nested_attributes_test.rb | 15 +++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/activerecord/lib/active_record/associations/association_collection.rb b/activerecord/lib/active_record/associations/association_collection.rb index 7e2a48bb85..7ecba45412 100644 --- a/activerecord/lib/active_record/associations/association_collection.rb +++ b/activerecord/lib/active_record/associations/association_collection.rb @@ -349,7 +349,11 @@ def load_target begin if !loaded? if @target.is_a?(Array) && @target.any? - @target = find_target.map { |f| i = @target.index(f); i ? @target.delete_at(i) : f } + @target + @target = find_target.map do |f| + i = @target.index(f) + t = @target.delete_at(i) if i + (t && t.changed?) ? t : f + end + @target else @target = find_target end diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index eab9e64a06..dc095c5416 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -468,15 +468,22 @@ def test_should_not_load_association_when_updating_existing_records def test_should_not_overwrite_unsaved_updates_when_loading_association @pirate.reload @pirate.send(association_setter, [{ :id => @child_1.id, :name => 'Grace OMalley' }]) - @pirate.send(@association_name).send(:load_target) - assert_equal 'Grace OMalley', @pirate.send(@association_name).target.find { |r| r.id == @child_1.id }.name + assert_equal 'Grace OMalley', @pirate.send(@association_name).send(:load_target).find { |r| r.id == @child_1.id }.name end def test_should_preserve_order_when_not_overwriting_unsaved_updates @pirate.reload @pirate.send(association_setter, [{ :id => @child_1.id, :name => 'Grace OMalley' }]) - @pirate.send(@association_name).send(:load_target) - assert_equal @pirate.send(@association_name).target.first.id, @child_1.id + assert_equal @child_1.id, @pirate.send(@association_name).send(:load_target).first.id + end + + def test_should_refresh_saved_records_when_not_overwriting_unsaved_updates + @pirate.reload + record = @pirate.class.reflect_on_association(@association_name).klass.new(:name => 'Grace OMalley') + @pirate.send(@association_name) << record + record.save! + @pirate.send(@association_name).last.update_attributes!(:name => 'Polly') + assert_equal 'Polly', @pirate.send(@association_name).send(:load_target).last.name end def test_should_take_a_hash_with_composite_id_keys_and_assign_the_attributes_to_the_associated_models -- GitLab