这两个实现在功能上是否等效?如果是这样,哪个更好?
# 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
更新:固定错字,因此示例读取验证
首先validate
,validates
是不同的方法-应该在validates
这里。
validates
会在提供的哈希中搜索所谓的_validates_default_keys
,这是一个内部数组[:if, :unless, :on, :allow_blank, :allow_nil , :strict]
。传递给validates
该数组的所有参数都被视为使用此方法附加到模型的所有验证器的通用选项。因此,如果您这样做:
validates :widget_color,
inclusion: {in: WIDGET_COLORS},
uniqueness: true,
allow_nil: true
allow_nil
将同时影响两个验证器,或等效于:
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
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句