【问题标题】:Rails associations within same model depending on attribute同一模型中的 Rails 关联取决于属性
【发布时间】: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


    【解决方案1】:

    只需将以下行更新到您的 Appointment 控制器即可完成工作:

    belongs_to :doctor_user, -> { doctor_user }, class_name: 'User'
    belongs_to :patient_user, -> { patient_user }, class_name: 'User'
    

    【讨论】:

    • 谢谢。这不起作用,实际上,添加这些行后我无法创建约会。我想我需要在我的模型中添加其他东西
    • 什么错误约会是给创造?您是否尝试过简单地查询为 Appointment.first.doctor_user ?因为,我在这里所做的是引用与用户模型中定义的范围的关联,它分别获得角色医生和患者的用户。
    • 您的解决方案可能有效,但这不是我想要的,问题是仅将医生用户设置为具有医生角色的用户。使用您的解决方案,患者在预约时也可能是医生,这不是我需要的
    【解决方案2】:

    我已通过将这些行添加到 Appointment 模型来解决此问题

    belongs_to :doctor_user, -> {where("role_id = ?", 1)}, class_name: 'User'
    belongs_to :patient_user, -> {where("role_id = ?", 2)}, class_name: 'User'
    

    【讨论】:

    • where(role_id: 1) 是首选方式
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多