dhouty
dhouty

Reputation: 1989

validate uniqueness of field in scope

I have a user model which has a polymorphic relationship to teachers, students, and admin. These three types of users each belong to a school. I would like to have it so the username of the user is unique within a school. How would I write the validations to accomplish this?

Here is what my models look like:

class User < ActiveRecord::Base
  belongs_to :profileable, :polymorphic => true
  delegate :school, :to => :profileable
end

class Student < ActiveRecord::Base
  belongs_to :school
  has_one :user, :as => :profileable
  delegate :name, :username, :to => :user
end

class Teacher < ActiveRecord::Base
  belongs_to :school
  has_one :user, :as => :profileable
  delegate :name, :username, :to => :user
end

class Admin < ActiveRecord::Base
  belongs_to :school
  has_one :user, :as => :profileable
  delegate :name, :username, :to => :user
end

Upvotes: 0

Views: 2383

Answers (1)

Jaap Haagmans
Jaap Haagmans

Reputation: 6332

I'm quite sure you will need to use a custom validator for this. The delegated attribute will not be usable in the User model. What you could do is also include the school_id in the User method and set it using before_validate every time. Then you'd be able to use the "simple" uniqueness validator:

validates :username, :uniqueness => {:scope => :school_id}

However, a custom validator joining the school_id of the profileable parent would probably be a cleaner way to go.

Upvotes: 2

Related Questions