提交 455a7633 编写于 作者: P Pascal Ehlert 提交者: Michael Koziarski

Nested attribute accessors should ignore new records with truthy _delete key.

Signed-off-by: NMichael Koziarski <michael@koziarski.com>
[#1861 state:committed]
上级 4e4f961c
......@@ -86,7 +86,8 @@ def self.included(base)
# For each key in the hash that starts with the string 'new' a new model
# will be instantiated. When the proc given with the <tt>:reject_if</tt>
# option evaluates to +false+ for a certain attribute hash no record will
# be built for that hash.
# be built for that hash. (Rejecting new records can alternatively be done
# by utilizing the <tt>'_delete'</tt> key. Scroll down for more info.)
#
# params = { 'member' => {
# 'name' => 'joe', 'posts_attributes' => {
......@@ -258,11 +259,14 @@ def should_destroy_nested_attributes_record?(allow_destroy, attributes)
# If a <tt>:reject_if</tt> proc exists for this association, it will be
# called with the attributes as its argument. If the proc returns a truthy
# value, the record is _not_ build.
#
# Alternatively, you can specify the <tt>'_delete'</tt> key to _not_ build
# a record. See should_destroy_nested_attributes_record? for more info.
def build_new_nested_attributes_record(association_name, attributes)
if reject_proc = self.class.reject_new_nested_attributes_procs[association_name]
return if reject_proc.call(attributes)
end
send(association_name).build(attributes)
send(association_name).build(attributes) unless should_destroy_nested_attributes_record?(true, attributes)
end
# Assigns the attributes to the record specified by +id+. Or marks it for
......
......@@ -233,6 +233,20 @@ def test_should_automatically_build_new_associated_models_for_each_entry_in_a_ha
assert_equal 'Privateers Greed', @pirate.send(@association_name).last.name
end
def test_should_remove_delete_key_from_arguments_hash_of_new_records
assert_nothing_raised ActiveRecord::UnknownAttributeError do
@pirate.send(association_setter, { 'new_1' => { '_delete' => '0' }})
end
end
def test_should_ignore_new_associated_records_with_truthy_delete_attribute
@pirate.send(@association_name).destroy_all
@pirate.reload.attributes = { association_getter => { 'new_1' => { :name => 'Grace OMalley' }, 'new_2' => { :name => 'Privateers Greed', '_delete' => '1' }}}
assert_equal 1, @pirate.send(@association_name).length
assert_equal 'Grace OMalley', @pirate.send(@association_name).first.name
end
def test_should_sort_the_hash_by_the_keys_before_building_new_associated_models
attributes = ActiveSupport::OrderedHash.new
attributes['new_123726353'] = { :name => 'Grace OMalley' }
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册