题
在Rails的2.X,您可以使用验证,以确保你有这样一个独特的组合值:
validates_uniqueness_of :husband, :scope => :wife
在相应的迁移也可能是这样的:
add_index :family, [:husband, :wife], :unique => true
这将确保丈夫/妻子的组合是在数据库中是唯一的。现在,在Rails 3中验证语法变化,scope属性似乎消失了。它现在看起来像:
validates :husband, :presence => true
任何知道如何才能实现在导轨3的组合验证? Rails的2.X验证仍然在Rails 3中工作,所以我仍然可以使用第一个例子,但它看起来很“老”,有没有更好的办法?
解决方案
包涵。在该加载ActiveModel方法只会验证的工作方式是寻找一个验证程序。
:presence => true
验看PresenceValidator
并传递选项:true
给校验器的初始化
我想你想
validates :husband, :presence => true, :uniqueness => {:scope => :wife}
(唯一性验证实际上是ActiveRecord的,加载ActiveModel不是的一部分,它是真正有趣的开发人员如何设置此。这是相当优雅。)
不隶属于 StackOverflow