Ruby-on-rails rails 3 验证多个属性的唯一性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3276110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
rails 3 validation on uniqueness on multiple attributes
提问by denisjacquemin
I use Rails 3.0.0.beta4
我使用 Rails 3.0.0.beta4
I want to add a validation on uniqueness on two attributes, that means that my model is valid if the couple of 'recorded_at'and 'zipcode'is unique.
我想对两个属性的唯一性添加验证,这意味着如果'recorded_at'和'zipcode'是唯一的,我的模型是有效的。
On one attribute here is the syntax
这里的一个属性是语法
validates :zipcode, :uniqueness => true
thanks
谢谢
回答by Christian Lescuyer
In Rails 2, I would have written:
在 Rails 2 中,我会这样写:
validates_uniqueness_of :zipcode, :scope => :recorded_at
In Rails 3:
在 Rails 3 中:
validates :zipcode, :uniqueness => {:scope => :recorded_at}
For multiple attributes:
对于多个属性:
validates :zipcode, :uniqueness => {:scope => [:recorded_at, :something_else]}
回答by Ray
Multiple Scope Parameters:
多个范围参数:
class TeacherSchedule < ActiveRecord::Base
validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
end
http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of
http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of
This should answer Greg's question.
这应该可以回答 Greg 的问题。
回答by Jesus
Dont work for me, need to put scopein plural
我不工作,需要把范围在复数
validates_uniqueness_of :teacher_id, :scopes=> [:semester_id, :class_id]
validates_uniqueness_of :teacher_id, :scope s=> [:semester_id, :class_id]

