Rails 3:验证组合值
在 Rails 2.x 中,您可以使用验证来确保拥有一个唯一的组合值,如下所示:
validates_uniqueness_of :husband, :scope => :wife
在相应的迁移中,它可能如下所示:
add_index :family, [:husband, :wife], :unique => true
这将确保丈夫/妻子的组合在数据库中是唯一的。现在,在 Rails 3 中,验证语法发生了变化,并且范围属性似乎消失了。现在看起来像:
validates :husband, :presence => true
知道如何在 Rails 3 中实现组合验证吗? Rails 2.x 验证在 Rails 3 中仍然有效,所以我仍然可以使用第一个示例,但它看起来很“旧”,有更好的方法吗?
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
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
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
耐心听我说。 ActiveModel 中的 validates 方法的工作方式是寻找 Validator。
<代码>:存在=> true 查找
PresenceValidator
并将选项:true
传递给验证器的初始值设定项。我想你想要
(唯一性验证器实际上是 ActiveRecord 的一部分,而不是 ActiveModel。开发人员如何设置它真的很有趣。它非常优雅。)
Bear with me. The way the validates method in ActiveModel works is to look for a Validator.
:presence => true
looks forPresenceValidator
and passes the options:true
to the validator's initializer.I think you want
(The uniqueness validator is actually part of ActiveRecord, not ActiveModel. It's really interesting how the developers set this up. It's quite elegant.)