1

params仅当更新或创建对象时它们存在时,我才需要验证模型中的少数属性。

 validates :attribute_a,format: {with: /some_regex/},  :if => lambda{ |object| object.attribute_a.present? }

就像attribute_a有多个在orattributes时可能不存在。而不是为它们中的每一个编写语句,有没有一种方法可以检查多个属性的存在,然后使用常见的验证来验证每个属性,例如or 。createdupdatedvalidatesinclusion_informat:{with:/some_regex/ }

我想要类似下面的代码,这显然是错误的。

validates :attribute_a,attribute_b,attribute_c,attribute_d,:format => {:with =>
 /some_regex/},  :if => lambda{ |object| object.attribute_name.present? }
4

1 回答 1

2

您可以使用validates_format_of

validates_format_of :attr_a, :attr_b, 
    with: /someregexp/,
    allow_blank: true

允许空白选项意味着如果属性不存在,则正则表达式不必匹配。

于 2013-09-03T16:30:00.603 回答