问题描述
这两个实现在功能上是否等效?如果是这样,哪个更好?
Are these two implementations functionally equivalent? If so, which is "better?"
# from a model
WIDGET_COLORS = %w(red yellow green)
validates :widget_color,
inclusion: {in: WIDGET_COLORS, allow_nil: true}
或
# from a model
WIDGET_COLORS = %w(red yellow green)
validates :widget_color,
inclusion: {in: WIDGET_COLORS},
allow_nil: true
更新:固定错字,因此示例读取 validates
UPDATE: fixed typo so example reads validates
推荐答案
首先validate
和validates
是不同的方法-在此处应为validates
.
Firstly validate
and validates
are different methods - it should be validates
here.
validates
将在提供的哈希中搜索所谓的_validates_default_keys
,它是内部数组[:if, :unless, :on, :allow_blank, :allow_nil , :strict]
.将此数组中传递给validates
的所有参数视为该方法附加到模型的所有验证器的通用选项.因此,如果您这样做:
validates
will search the supplied hash for so-called _validates_default_keys
, which is an internal array [:if, :unless, :on, :allow_blank, :allow_nil , :strict]
. All the arguments passed to validates
being in this array are treated as common options for all the validators attached to the model with this method. So if you do:
validates :widget_color,
inclusion: {in: WIDGET_COLORS},
uniqueness: true,
allow_nil: true
allow_nil
将同时影响两个验证器,或等效于:
allow_nil
will affect both of the validators, or is equivalent of:
validates :widget_color,
inclusion: {in: WIDGET_COLORS, allow_nil: true},
uniqueness: {allow_nil: true}
另一方面
validates :widget_color,
inclusion: {in: WIDGET_COLORS, allow_nil: true},
uniqueness: true
它只会影响为其定义的验证器(在本例中为InclusionValidator
)
it will only affect the validator it is defined for (in this case InclusionValidator
)
这篇关于Rails 4验证:进行包含时,将allow_nil放在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!