Skip to content

Commit

Permalink
Fix for nested_attributes with has_many association fails when a sing…
Browse files Browse the repository at this point in the history
…le record is being updated.

[#5705 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
  • Loading branch information
Neeraj Singh authored and josevalim committed Sep 27, 2010
1 parent 67a8385 commit 7f74323
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
7 changes: 6 additions & 1 deletion activerecord/lib/active_record/nested_attributes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,12 @@ def assign_nested_attributes_for_collection_association(association_name, attrib
end

if attributes_collection.is_a? Hash
attributes_collection = attributes_collection.sort_by { |index, _| index.to_i }.map { |_, attributes| attributes }
keys = attributes_collection.keys
attributes_collection = if keys.include?('id') || keys.include?(:id)
Array.wrap(attributes_collection)
else
attributes_collection.sort_by { |i, _| i.to_i }.map { |_, attributes| attributes }
end
end

association = send(association_name)
Expand Down
8 changes: 8 additions & 0 deletions activerecord/test/cases/nested_attributes_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,14 @@ def test_reject_if_with_a_proc_which_returns_true_always
assert_equal 's1', ship.reload.name
end

def test_has_many_association_updating_a_single_record
Man.accepts_nested_attributes_for(:interests)
man = Man.create(:name => 'John')
interest = man.interests.create(:topic => 'photography')
man.update_attributes({:interests_attributes => {:topic => 'gardening', :id => interest.id}})
assert_equal 'gardening', interest.reload.topic
end

end

class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
Expand Down

0 comments on commit 7f74323

Please sign in to comment.