验证范围内的字段唯一性

时间:2013-09-18 03:56:12

标签: ruby-on-rails validation

我有一个与教师,学生和管理员有多态关系的用户模型。这三类用户各自属于一所学校。我想拥有它,因此用户的用户名在学校内是唯一的。我如何编写验证来完成此任务?

以下是我的模型:

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

1 个答案:

答案 0 :(得分:1)

我很确定您需要使用自定义验证器。委托属性在User模型中不可用。您可以执行的操作还包括User方法中的school_id,并且每次都使用before_validate进行设置。然后你就可以使用“简单”唯一性验证器了:

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

但是,加入可分析父级的school_id的自定义验证器可能是一种更简洁的方法。