9

I wanted to clarify the behavior of multi-scope uniqueness validation. The documentation says:

Or even multiple scope parameters. For example, making sure that a teacher can only be on the schedule once per semester for a particular class.

class TeacherSchedule < ActiveRecord::Base
  validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
end

My understanding of this is that I could have a teacher teaching two classes in the same semester but not the same class, and I could have a teacher teaching the same class in different semesters. Is this correct? All 3 fields must match some existing record in order for validation to fail?

Is there a way to validate it so that it fails if either semester_id or class_id matches?

4

2 回答 2

11

My understanding of this is that I could have a teacher teaching two classes in the same semester but not the same class, and I could have a teacher teaching the same class in different semesters. Is this correct? All 3 fields must match some existing record in order for validation to fail?

Yes, this is correct. Thing about it as "for every unique value of scope, the field can only show up once." When scope is an array, a "unique value for scope" is a combination of the fields' values.

Is there a way to validate it so that it fails if either semester_id or class_id matches?

So a teacher should never teach twice in a semester, and also should never ever teach the same class, even in a different semester? That doesn't seem right, but you could do that with a validation on each:

class TeacherSchedule < ActiveRecord::Base
  validates_uniqueness_of :teacher_id, :scope => :semester_id
  validates_uniqueness_of :teacher_id, :scope => :class_id
end
于 2012-12-01T20:19:41.873 回答
0

我刚刚了解了唯一性验证如何与范围一起工作,我想与大家分享。

假设您在组织中有多个部门,并且任何员工也可以同时属于两个或多个部门。为了确保员工的电子邮件 ID 在每个部门中是唯一的,我们使用范围。

通过这样做,我们可以确保没有两个具有相同电子邮件地址的员工在同一个部门工作。我们还可以找出特定员工所在的所有部门。

简单来说,使用范围的唯一性验证适用于两个属性(在我们的例子中是电子邮件,部门)。

于 2017-01-04T10:26:28.073 回答