Rails 3:验证组合值 [英] Rails 3: Validate combined values
问题描述
在Rails 2.x中,您可以使用验证来确保具有唯一的组合值,如下所示:
In Rails 2.x you can use validations to make sure you have a unique combined value like this:
validates_uniqueness_of :husband, :scope => :wife
在相应的迁移中,它可能看起来像这样:
In the corresponding migration it could look like this:
add_index :family, [:husband, :wife], :unique => true
这将确保丈夫/妻子组合在数据库中是唯一的.现在,在Rails 3中,验证语法已更改,并且scope属性似乎消失了.现在看起来像:
This would make sure the husband/wife combination is unique in the database. Now, in Rails 3 the validation syntax changed and the scope attribute seems to be gone. It now looks like:
validates :husband, :presence => true
有什么想法可以在Rails 3中实现组合验证吗? Rails 2.x验证仍然可以在Rails 3中使用,因此我仍然可以使用第一个示例,但是它看起来太旧"了,有更好的方法吗?
Any idea how I can achieve the combined validation in Rails 3? The Rails 2.x validations still work in Rails 3 so I can still use the first example but it looks so "old", are there better ways?
推荐答案
与我同在. ActiveModel中validates方法的工作方式是寻找一个Validator.
Bear with me. The way the validates method in ActiveModel works is to look for a Validator.
:presence => true
查找PresenceValidator
,并将选项:true
传递给验证程序的初始化程序.
:presence => true
looks for PresenceValidator
and passes the options: true
to the validator's initializer.
我认为你想要
validates :husband, :presence => true, :uniqueness => {:scope => :wife}
(唯一性验证器实际上是ActiveRecord的一部分,而不是ActiveModel的一部分.开发人员如何进行设置非常有趣.它非常优雅.)
(The uniqueness validator is actually part of ActiveRecord, not ActiveModel. It's really interesting how the developers set this up. It's quite elegant.)
这篇关于Rails 3:验证组合值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!