如何仅允许指定具有指定角色的用户?

时间:2013-09-13 11:41:27

标签: ruby-on-rails ruby validation cancan

我拥有CanCan授权的User模型。

因此,用户拥有此数组的role属性:=> ['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

我应该如何编写验证程序以仅为Shifts创建doctors而不允许在user_id属性不是patient ID时创建转移?

3 个答案:

答案 0 :(得分:0)

您应该编写自定义验证方法。这样的事情应该适合你。

validate :check_doctor
def check_doctor
  errors.add(:doctor, "User is not a doctor") unless self.doctor && self.doctor.role == "doctor" 
end

答案 1 :(得分:0)

试试这个:

validate :check_for_patient

private
  def check_for_patient
    errors.add(:base, 'error message') if self.doctor && self.doctor.role == 'patient'
  end

答案 2 :(得分:0)

嗯,自定义检查器(如在其他答案中)可以正常工作,但考虑将User的概念与系统中的角色分开。如果某些Doctor想要成为Patient

,该怎么办?

也许为DoctorsPatients创建单独的表?

因此,实施支票很容易。即为Shift ...

创建Patient是不可能的

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

相关问题