2014-11-06 49 views
1

这两个实现在功能上是否等同?如果是这样,哪个更好?Rails 4验证:在进行包含时,在哪里放置allow_nil?

# 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 

UPDATE:固定错字所以示例读取验证

回答

6

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