【发布时间】:2015-10-12 22:50:37
【问题描述】:
(参见下面的示例项目链接)
我的工作:
我使用 Rails 中的单表继承处理许多用户类型,例如:
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 类型:Doctor、Nurse、Employee 和 Patient。
我想做的是让所有患者的医生、护士和员工都通过这样的电话:
@this_patient.providers # => [doctor1, nurse2, employee3]
为了实现这一点,我考虑删除患者和提供者之间的 3 种不同类型的连接表(例如医生_患者_关系),并将它们全部替换为一个名为 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
问题是,由于我没有类名提供程序,rails 会抛出错误:
NoMethodError: undefined method `_reflect_on_association' for Provider:Class
如果我致电 @this_patient.providers,我如何让 rails 去查看医生、护士和员工?
编辑
我有一个示例项目要开始工作,请查看自述文件以获取说明并进行设置:
https://github.com/waleedasif322/group-user-types-example-rails
【问题讨论】:
标签: ruby-on-rails single-table-inheritance