简体   繁体   English

如果其他验证失败,Rails ActiveRecord在线状态验证是否有用?

[英]Are Rails ActiveRecord presence validations useful if other validations would fail?

If I have validations that require certain values in a field, like a format: { with: some_regex } or an inclusion: { in: some_array } that will fail on blank or nil, is setting the validation presence: true useful in any way? 如果我的验证需要在字段中输入某些值,例如format: { with: some_regex }inclusion: { in: some_array }将失败为空白或nil,那么是否设置验证presence: true有用吗? In the same situation, is the length: { } validation useful if the other validations would fail? 在相同情况下,如果其他验证失败,则length: { }验证是否有用?

Similarly, could a length validation of {1..n} preclude the need for a presence validation? 同样,长度验证为{1..n}是否可以排除在场验证的需要?

I'm trying to learn if there is something more going on or if the checks are simply redundant. 我正在尝试了解是否还有其他事情在进行,或者检查是否仅仅是多余的。 For instance, the Rails Tutorial has a presence: true validation on the email address but the format validation should not allow a blank or nil address. 例如,Rails教程中presence: true对电子邮件地址的presence: true验证,但格式验证不应包含空白或零地址。 Seems redundant, or is it style/convention? 似乎是多余的,还是样式/惯例?

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. 如果您使用诸如format: regex类的format: regex并且可以保证(通过单元测试足够容易)空白或nil属性将导致整个记录无效,那么是的,您不需要验证其存在。 Same with the inclusion situation, and the length situation. inclusion情况和length情况相同。

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. 但是,如果您已经针对具有空白或无属性的情况对模型进行了全面测试,并且当前的验证可以达到预期的结果,那么您就可以了。

Validation of presence if weaker then anything mentioned. 如果存在弱点,则验证存在。 I'd rather not put 我宁愿不放

validates presence: true

having, for instance, 例如

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

as the later already would cover the situation with the field having nil value. 因为后面已经覆盖了字段值为nil的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM