Rails 4验证:进行包含时,将allow_nil放在哪里? [英] Rails 4 Validation: where to put the allow_nil when doing an inclusion?

查看:106
本文介绍了Rails 4验证:进行包含时,将allow_nil放在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个实现在功能上是否等效?如果是这样,哪个更好?

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

推荐答案

首先validatevalidates是不同的方法-在此处应为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放在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆