【发布时间】:2021-10-11 01:38:58
【问题描述】:
我正在使用 devise 和 cancancan 构建一个 rails 应用程序,并且我正在尝试在同一模型中创建关联。我有一个用户模型、一个角色模型和一个约会模型。用户可以具有医生或患者的角色。我想创建一个关联,以便患者可以与医生创建约会。我设法创建了关联,但我不知道如何让患者只与医生预约,并且只能以这种方式。 我的模型是这样的:
用户模型
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
belongs_to :role, optional: true
validates :name, :DOB, presence: true
has_many :doctor_user_appointments, class_name: 'Appointment', foreign_key: 'doctor_user_id', dependent: :destroy
has_many :patient_user_appointments, class_name: 'Appointment', foreign_key: 'patient_user_id', dependent: :destroy
before_save :assign_role
scope :doctor_user, -> {where("role_id = ?", 1)
scope :patient_user, -> {where("role_id = ?", 2)
def admin?
role.name == 'Admin'
end
def doctor?
role.name == 'Doctor'
end
def patient?
role.name == 'Patient'
end
def assign_role
self.role = Role.find_by name: 'Patient' if role.nil?
end
end
榜样
class Role < ApplicationRecord
has_many :users, dependent: :restrict_with_exception
end
预约模式
class Appointment < ApplicationRecord
belongs_to :doctor_user, class_name: 'User'
belongs_to :patient_user, class_name: 'User'
end
使用这些模型,我可以在两个用户的医生用户和患者用户之间创建约会,但关联不区分谁具有“医生”角色和谁具有“患者”角色。我尝试过使用范围,但它不起作用。 我基本上想要的是医生用户只能是角色“医生”的用户或角色 ID = 1 的用户,而患者用户只能是角色 ID = 2 或角色“病人”的用户
欢迎任何帮助,因为我很困惑 提前致谢
【问题讨论】:
标签: ruby-on-rails model scope associations