我想对同一个字段多次使用相同的验证类型(但根据条件使用不同的选项),如下例所示:
validates :something, :length => { :minimum => 1, :if => :some_condition1 }
validates :something, :length => { :minimum => 2, :maximum => 20, :if => :some_condition2 }
validates :something, :length => { :minimum => 10, :unless => :some_condition3 }
但是这种方式无法正常工作,因为只有最后一次验证才适用。 有没有其他方法可以做这样的事情?
答案 0 :(得分:2)
正确的语法是:
validates :something, :length => { :minimum => 1 }, :if => :some_condition1
validates :something, :length => { :minimum => 2, :maximum => 20 }, :if => :some_condition2
validates :something, :length => { :minimum => 10 }, :unless => :some_condition3
采取长度选项之外的条件。
另外,您可以查看Conditional Validations了解更多信息
答案 1 :(得分:0)
validate :length_of_something
def length_of_something
length = self.something.length
valid = case
when some_condition1
lengh >= 1
when some_condition2
length >= 2 && length <= 20
when some_condition3
length > 10
end
errors.add(:something, :invalid) unless valid
end