`reject_if` 的基本原理是什么?
What is the rationale for `reject_if`?
我在茧的 README, and also in the documentation for Nested Attributes 中遇到了 reject_if
。当关联的活动记录对象可以确定它们是否有效时,使用 reject_if
的基本原理是什么?
对于嵌套对象,您可能不想尝试提交 :all_blank
的记录,或者出于任何其他您可能想要检查的原因。关键是,一个空的或不完整的(在某种程度上)对象可以通过这种方式简单地不被构建/添加到嵌套对象集合中。
验证有不同的用途。例如,如果一个空对象未能通过验证,那么整个表单提交都将失败。 reject_if
方法允许在这种情况下通过在验证触发之前将对象从考虑中移除来成功提交。
Rails 指南描述了 :reject_if
的基本原理,但它没有明确地将此选项与仅验证子对象进行比较:
It is often useful to ignore sets of fields that the user has not
filled in. You can control this by passing a :reject_if
proc to
accepts_nested_attributes_for
. This proc will be called with each
hash of attributes submitted by the form. If the proc returns false
then Active Record will not build an associated object for that hash.
The example below only tries to build an address if the kind
attribute is set.
class Person < ActiveRecord::Base
has_many :addresses
accepts_nested_attributes_for :addresses, reject_if: lambda {|attributes| attributes['kind'].blank?}
end
As a convenience you can instead pass the symbol :all_blank
which
will create a proc that will reject records where all the attributes
are blank excluding any value for _destroy
.
我在茧的 README, and also in the documentation for Nested Attributes 中遇到了 reject_if
。当关联的活动记录对象可以确定它们是否有效时,使用 reject_if
的基本原理是什么?
对于嵌套对象,您可能不想尝试提交 :all_blank
的记录,或者出于任何其他您可能想要检查的原因。关键是,一个空的或不完整的(在某种程度上)对象可以通过这种方式简单地不被构建/添加到嵌套对象集合中。
验证有不同的用途。例如,如果一个空对象未能通过验证,那么整个表单提交都将失败。 reject_if
方法允许在这种情况下通过在验证触发之前将对象从考虑中移除来成功提交。
Rails 指南描述了 :reject_if
的基本原理,但它没有明确地将此选项与仅验证子对象进行比较:
It is often useful to ignore sets of fields that the user has not filled in. You can control this by passing a
:reject_if
proc toaccepts_nested_attributes_for
. This proc will be called with each hash of attributes submitted by the form. If the proc returnsfalse
then Active Record will not build an associated object for that hash. The example below only tries to build an address if thekind
attribute is set.class Person < ActiveRecord::Base has_many :addresses accepts_nested_attributes_for :addresses, reject_if: lambda {|attributes| attributes['kind'].blank?} end
As a convenience you can instead pass the symbol
:all_blank
which will create a proc that will reject records where all the attributes are blank excluding any value for_destroy
.