【问题标题】:Rails 4 Validation: where to put the allow_nil when doing an inclusion?Rails 4 验证:在进行包含时将 allow_nil 放在哪里?
【发布时间】:2014-11-06 01:40:34
【问题描述】:

这两种实现在功能上是否相同?如果是这样,哪个“更好”?

  # 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

【问题讨论】:

    标签: ruby-on-rails validation inclusion


    【解决方案1】:

    首先validatevalidates 是不同的方法——这里应该是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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-22
      相关资源
      最近更新 更多