0

如果我的验证需要某个字段中的某些值,例如在空白或 nil 上失败的 aformat: { with: some_regex }或 an inclusion: { in: some_array },那么设置验证是否presence: true有用?在同样的情况下,length: { }如果其他验证失败,验证是否有用?

同样,{1..n} 的长度验证是否可以排除存在验证的需要?

我正在尝试了解是否有更多事情发生,或者检查是否只是多余的。例如,Rails 教程presence: true对电子邮件地址进行了验证,但格式验证不应允许空白或零地址。似乎是多余的,还是风格/惯例?

4

2 回答 2

1

If you're using something like format: regex and you can guarantee (easy enough through a unit test) that a blank or nil attribute will cause the whole record to be invalid, then yes you don't need to validate the presence. Same with the inclusion situation, and the length situation.

In general, adding more validations isn't necessarily a bad thing. But, if you've thoroughly tested your model for situations with blank or nil attributes and your current validations achieve the desired result, then you're fine.

于 2012-05-11T19:07:06.553 回答
0

如果比提到的任何内容,则验证存在。我宁愿不放

validates presence: true

有,例如,

validates format: { with: some_regex }, allow_blank: false

因为后者已经涵盖了具有nil价值的领域的情况。

于 2012-05-11T19:10:32.823 回答