[英]rails validation: :allow_nil and :inclusion both needed at the same time
[英]Rails 4 Validation: where to put the allow_nil when doing an inclusion?
這兩個實現在功能上是否等效? 如果是這樣,哪個更好?
# 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
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.