Rails 3: Validate combined values

二次信任 提交于 2019-12-03 03:01:17

问题


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?


回答1:


Bear with me. The way the validates method in ActiveModel works is to look for a Validator.

:presence => true looks for PresenceValidator and passes the options: true to the validator's initializer.

I think you want

validates :husband, :presence => true, :uniqueness => {:scope => :wife}

(The uniqueness validator is actually part of ActiveRecord, not ActiveModel. It's really interesting how the developers set this up. It's quite elegant.)



来源:https://stackoverflow.com/questions/2533502/rails-3-validate-combined-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!