0

I have User model with CanCan authorisation.

So user have role attribute from this array: => ['doctor', 'patient']

class Shift < ActiveRecord::Base
  belongs_to :doctor, class_name: "User", foreign_key: :user_id
  belongs_to :day

  validates :shift, presence: true
  validates :cardiologist, presence: true
end

How should I write validator to allow create Shifts only for doctors and not allow to create shift where user_id attribute is not a patient id?

4

3 回答 3

0

您应该编写自定义验证方法。像这样的东西应该为你做。

validate :check_doctor
def check_doctor
  errors.add(:doctor, "User is not a doctor") unless self.doctor && self.doctor.role == "doctor" 
end
于 2013-09-13T11:52:04.480 回答
0

尝试这个:

validate :check_for_patient

private
  def check_for_patient
    errors.add(:base, 'error message') if self.doctor && self.doctor.role == 'patient'
  end
于 2013-09-13T11:52:29.640 回答
0

好吧,自定义检查器(就像其他答案一样)可以正常工作,但请考虑将User系统中的概念和角色分开。如果有人Doctor想成为一个Patient怎么办?

Doctors也许为and创建单独的表Patients

因此,很容易实施您的检查。即不可能ShiftPatient...创建

使用 STI(单表继承)方法,处理这样的事情很快就会变得混乱(处理太多)。

于 2013-09-13T12:02:56.297 回答