From 534030cf83b078b10c08ffb587cc56e86773ea8c Mon Sep 17 00:00:00 2001 From: Olek Janiszewski Date: Tue, 26 Feb 2013 03:06:35 +0100 Subject: Do not overwrite manually built records during one-to-one nested attribute assignment For one-to-one nested associations, if you build the new (in-memory) child object yourself before assignment, then the NestedAttributes module will not overwrite it, e.g.: class Member < ActiveRecord::Base has_one :avatar accepts_nested_attributes_for :avatar def avatar super || build_avatar(width: 200) end end member = Member.new member.avatar_attributes = {icon: 'sad'} member.avatar.width # => 200 --- activerecord/test/cases/nested_attributes_test.rb | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'activerecord/test/cases') diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index b6e140b912..165b7454b7 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -131,6 +131,20 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase assert_equal 's1', ship.reload.name end + def test_reuse_already_built_new_record + pirate = Pirate.new + ship_built_first = pirate.build_ship + pirate.ship_attributes = { name: 'Ship 1' } + assert_equal ship_built_first.object_id, pirate.ship.object_id + end + + def test_do_not_allow_assigning_foreign_key_when_reusing_existing_new_record + pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?") + pirate.build_ship + pirate.ship_attributes = { name: 'Ship 1', pirate_id: pirate.id + 1 } + assert_equal pirate.id, pirate.ship.pirate_id + end + def test_reject_if_with_a_proc_which_returns_true_always_for_has_many Man.accepts_nested_attributes_for :interests, :reject_if => proc {|attributes| true } man = Man.create(name: "John") -- cgit v1.2.3