Skip to content
Browse files

Fix for nested_attributes with has_many association fails when a sing…

…le record is being updated.

[#5705 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
  • Loading branch information...
1 parent 67a8385 commit 7f743233c4e276d1799451478e6718589d270cbd @neerajdotname neerajdotname committed with josevalim
View
7 activerecord/lib/active_record/nested_attributes.rb
@@ -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)
View
8 activerecord/test/cases/nested_attributes_test.rb
@@ -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

0 comments on commit 7f74323

Please sign in to comment.
Something went wrong with that request. Please try again.