Home > Blockchain >  has_many :through within same model
has_many :through within same model

Time:02-17

I have User model in my database. It has role. role can be either patient or doctor. I want to maintain doctor_patient table.

doctor_patient.rb

belongs_to :doctor,  class_name: 'User'
belongs_to :patient, class_name: 'User'

a patient can belong to many doctors and a docor can have many patients. I am familier to regular or normal has_many through association but facing issues related to this scenarios where I have role in user model.

user.rb

user 
has_many :doctor_patients
has_many :patients, :through => :doctor_patients, :class_name=> "User"

patient 
has_many :doctor_patients
has_many :doctors, :through=> :doctor_patients, :class_name=> "User"

CodePudding user response:

In ActiveRecord the assocation metadata (the reflection) is strored in a class attribute as a hash and the name is used as the key. So when you define multiple assocations with the same name you're just overwriting your previous assocation.

The solution is to use unique names for each assocation:

class User < ApplicationController
  has_many :doctor_patients_as_doctor, 
    foreign_key: :doctor_id,
    class_name: 'DoctorPatient'
  has_many :patients, 
    through: :doctor_patients_as_doctor

  has_many :doctor_patients_as_patient, 
    foreign_key: :patient_id,
    class_name: 'DoctorPatient'
  has_many :doctors, 
    through: :doctor_patients_as_patient
end

Also make sure you pluralize the table correctly and name it doctor_patients.

  • Related