我的資料庫中有用戶模型。它有作用。角色可以是患者或醫生。我想維護醫生_患者表。
doctor_patient.rb
belongs_to :doctor, class_name: 'User'
belongs_to :patient, class_name: 'User'
一個病人可以屬于很多醫生,一個醫生可以有很多病人。我通過關聯更熟悉常規或正常的 has_many,但面臨與我在用戶模型中扮演角色的場景相關的問題。
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"
uj5u.com熱心網友回復:
在 ActiveRecord 中,關聯元資料(反射)作為散列存盤在類屬性中,名稱用作鍵。因此,當您定義多個具有相同名稱的關聯時,您只是覆寫了之前的關聯。
解決方案是為每個關聯使用唯一名稱:
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
還要確保正確地復數表格并為其命名doctor_patients。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/426357.html
