Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple scope uniqueness validation

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?

like image 577
mushroom Avatar asked Dec 01 '12 20:12

mushroom


People also ask

What is scope in validation in Rails?

The scope option to the Rails uniqueness validation rule allows us to specify additional columns to consider when checking for uniqueness. class Project < ApplicationRecord belongs_to :account has_many :tasks validates :name, presence: true, uniqueness: { scope: :account_id } end.

What is the difference between validate and validates in Rails?

So remember folks, validates is for Rails validators (and custom validator classes ending with Validator if that's what you're into), and validate is for your custom validator methods.


1 Answers

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
like image 158
Michelle Tilley Avatar answered Oct 21 '22 23:10

Michelle Tilley