如何验证提交的 ActiveRecord 的单个属性而不是其所有属性?
我正在使用 Ruby on Rails 3,我想验证提交的 ActiveRecord 的单个属性而不是其所有属性。
例如,在我的模型中:
validates :firstname, :presence => true, ...
validates :lastname, :presence => true, ...
我想分别对 :firstname
和 :lastname
运行验证。 可能吗?如果是这样,我该怎么做?
PS:我知道出于验证目的,有“validates_presence_of”、“validates_confirmation_of”等方法,...,但我只想使用上面的代码。
I am using Ruby on Rails 3 and I would like to validate a single attribute for a submitting ActiveRecord instead of all its attributes.
For example, in my model I have:
validates :firstname, :presence => true, ...
validates :lastname, :presence => true, ...
I would like to run validation on the :firstname
and on the :lastname
separately. Is it possible? If so, how can I make that?
P.S.: I know that for validation purposes there are methods like "validates_presence_of", "validates_confirmation_of", ..., but I would like to use only the above code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在模型上设置虚拟属性,然后根据该属性进行条件验证。
您可以在 http://railscasts.com/episodes/41-conditional-validations 找到有关此内容的截屏视频
You can setup a virtual attribute on your model, and then do conditional validation depending on that attribute.
You can find a screencast about this at http://railscasts.com/episodes/41-conditional-validations
您可以删除上面代码的第二行,这样它就显示为:
不会对 :lastname 执行任何验证。
问候
罗宾
You can just delete the second line of your code above so it reads:
No validation will then be performed on the :lastname.
Regards
Robin