简体   繁体   English

rails 3验证多个属性的唯一性

[英]rails 3 validation on uniqueness on multiple attributes

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 谢谢

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]}

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. 这应该回答格雷格的问题。

Dont work for me, need to put scope in plural 不要为我工作,需要将范围放在复数

validates_uniqueness_of :teacher_id, :scope s => [:semester_id, :class_id] validates_uniqueness_of:teacher_id,:scope s => [:semester_id,:class_id]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM