在哪里以及如何对模型进行自定义验证?
假设我们有一个简单的模型,它存储两个整数:最小值和最大值。我们想强制 min <= max
。
class MinMax
include MongoMapper::Document
key :min, Integer
key :max, Integer
validate_presence_of :min, :max
end
1)如何验证 min 确实等于或小于 max?
2)如果您认为这不是模型的责任,那么应该在哪里以及由谁进行验证?
Lets say we have a simple model that stores two integers, the min and the max. We would like to force min <= max
.
class MinMax
include MongoMapper::Document
key :min, Integer
key :max, Integer
validate_presence_of :min, :max
end
1) How would you validate that min is indeed equal or less than max?
2) If you don't think this is the responsibility of the model, then where and who should do that validation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会反过来回答你的问题。对于问题 2,这样的验证绝对是模型的责任。几乎所有程序的核心逻辑都属于您的模型;控制器仅用于从 HTTP 请求映射到适当的模型方法。
对于1,只需使用
validates
调用自定义验证方法如果您想要自定义错误消息,请在验证中显式添加错误消息:
I'll answer your questions in reverse. For question 2, validations such as this absolutely are the responsibility of the model. Pretty much anything that is the core logic of your program belongs in your models; controllers are only for mapping from HTTP requests to the appropriate model methods.
For 1, just use
validates
to call a custom validation methodIf you want a custom error message, add the error message explicitly in the validation:
类级别方法是
validate
,而不是validates
...The class level method is
validate
, notvalidates
...