我是 Ruby on Rails 的新手。而且我不明白,為什么模型中只能有一個has_many?
class Physician < ApplicationRecord
has_many :appointments
has_many :patients, through: :appointments
has_many :diagnoses
has_many :patients, through: :diagnoses
end
class Appointment < ApplicationRecord
belongs_to :physician
belongs_to :patient
end
class Diagnosis < ApplicationRecord
belongs_to :physician
belongs_to :patient
end
class Patient < ApplicationRecord
has_many :appointments
has_many :physicians, through: :appointments
has_many :diagnoses
has_many :physicians, through: :diagnoses
end
uj5u.com熱心網友回復:
在軌道上的關聯設定宏(belongs_to,has_one,has_many和has_and_belongs_to_many)寫AssocationReflection包含所有哪些被保持在所述ASSOCATION元資料散列作為一個類屬性。
關聯的名稱是用于存盤反射的鍵。當您宣告具有相同名稱的多個關聯時,您只是覆寫了以前的關聯 - 這實際上可能很有用,例如在繼承關聯或猴子補丁時。
在舊版本的 Rails 中,重新定義has_many through:關聯可能會HasManyThroughOrderError由于實施中的缺陷而引發,該缺陷已在 2018 年修復并向后移植。
您真正應該做的是為每個關聯定義唯一的名稱。
class Physician < ApplicationRecord
has_many :appointments
has_many :patients, through: :appointments
has_many :diagnosed_patients,
through: :diagnoses,
source: :patient
end
class Patient < ApplicationRecord
has_many :appointments
has_many :physicians, through: :appointments
has_many :diagnoses
has_many :diagnosing_physicians,
through: :diagnoses,
source: :physicians
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/421026.html
標籤:
