如何在 Single Table Inheritance 类 中将多个模型组合在一个名称下

How to group together multiple models under one name in Single Table Inheritance classes

(请参阅下面的 link 示例项目)

我的工作:

我在 Rails 中使用单一 Table 继承处理许多用户类型,例如:

class User < ActiveRecord::Base
  self.inheritance_column = :meta_type
  scope :doctors, -> { where(meta_type: 'Doctor') }
  scope :patients, -> { where(meta_type: 'Patient') }
  scope :nurses, -> { where(meta_type: 'Nurse') }
  scope :employees, -> { where(meta_type: 'Employee') }

end

class Doctor < User
  has_many :doctor_patient_relations
  has_many :patients, :through => :doctor_patient_relations
  has_many :doctor_nurse_relations
  has_many :nurses, :through => :doctor_nurse_relations
  ...
  # More join tables between each type of user
end

class Patient < User
  has_many :doctor_patient_relations
  has_many :doctors, :through => :doctor_patient_relations
  has_many :nurse_patient_relations 
  has_many :nurses, :through => :nurse_patient_relations
  has_many :employee_patient_relations
  has_many :employees, :through => :employee_patient_relations
end

我总共有 4 个 User 类型:DoctorNurseEmployeePatient

我希望能够通过这样的电话联系所有患者的医生、护士和员工:

@this_patient.providers # => [doctor1, nurse2, employee3]

为了实现这一点,我考虑删除患者和提供者之间的 3 种不同类型的连接 table(例如 doctor_patient_relations),并将它们全部替换为单个 table 称为 provider_patient_relations。

我添加的新文件以尝试使其正常工作:

class ProviderPatientRelation < ActiveRecord::Base
  belongs_to :provider, class_name: "User", :foreign_key => :provider_id
  belongs_to :patient, class_name: "User", :foreign_key => :patient_id
end

我还在 User.rb 文件中添加了这个:

class User < ActiveRecord::Base
  ...
  has_many :provider_patient_relations
  has_many :patients, -> { where meta_type: 'Doctor' || 'Nurse' }, :through => :provider_patient_relations, :inverse_of => :patient
  has_many :providers, -> { where meta_type: 'Patient' }, :through => :provider_patient_relations, :inverse_of => :provider
end

问题是,由于我没有 class 名称提供程序,rails 抛出错误:

NoMethodError: undefined method `_reflect_on_association' for Provider:Class

如果我打电话给 @this_patient.providers,我如何告诉 rails 查看医生、护士和员工?

编辑

我有一个示例项目可以开始工作,请查看自述文件以获取说明并进行设置:

https://github.com/waleedasif322/group-user-types-example-rails

你们非常亲密。在您的 Patient 模型中,您使用 'as' 就好像您试图将其分配为别名一样。但是 'as' 用于多态关联...我用以下内容替换了您的 Patient 模型,并且能够在控制台中成功调用 Patient.first.providers

class Patient < User
    has_many :patient_provider_relations
    has_many :providers, through: :patient_provider_relations, source_type: "User"
end

然后我将 Patient Provider Relation 关联移至关注点:

module Patientable
    extend ActiveSupport::Concern

    included do

        belongs_to :provider, polymorphic: true
        has_many :patient_provider_relations, as: :provider
        has_many :patients, through: :patient_provider_relations, source: :patient

    end
end

最后在您的 Doctor、Nurse 和 Employee 模型中添加了 include Patientable