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?
Yes, this is correct. Thing about it as “for every unique value of
scope, the field can only show up once.” Whenscopeis an array, a “unique value for scope” is a combination of the fields’ values.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: