[英]rails has_many vs has_many through?
我已經閱讀了關於關系標識符has_many
和has_many through
。 我似乎無法理解的是它們之間的區別。 例如,如果我有 3 個模型,醫生、預約和患者
class Doctor< ActiveRecord::Base
has_many :appointments
has_many :patients, through: :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :doctor
belongs_to :patient
end
class Patient < ActiveRecord::Base
has_many :appointments
has_many :doctors, through: :appointments
end
我不能說 Doctor has_many :patients 和 Patient has_many :doctors 和他們有關系嗎? 通過約會來做這件事的目的是什么?
謝謝
你是對的。 如果你說一個醫生has_many :patients
和一個病人has_many :doctors
,那么他們將是相關的。
但是,我認為本教程的目的是多對多關聯。
如果醫生模型和患者模型是由相關has_many
,然后醫生專門擁有一個病人和病人擁有一名醫生。 但通常情況下,情況可能並非如此。 一個醫生可以有很多病人,而這些病人不一定只屬於一個醫生; 他們可能有其他醫生。
這就是多對多關聯出現的時候。在多對多關聯中,一個對象可以有許多屬於它的對象,但不是唯一的。 這就像醫生模型和患者模型之間的關聯。
有兩種方法可以創建多對多關聯:
has_and_belongs_to_many
has_many
#something through:
#joining table 在您的情況下,您使用的是第二種方式,即連接表assocation
。
查看這個Railscast對這兩個的詳細解釋。 此外,這個關於關聯的官方 Rails 文檔也會有所幫助。
使用“通過”表的唯一原因是當您想使用中間表中包含的一些相關數據時,在這種情況下,是與醫生和患者相關的預約數據。
此外, has_many
需要相關的belongs_to
,反之亦然,因此您必須在兩個模型中使用has_and_belongs_to_many
來表示多對多關系,並創建相應的連接表來配合它。
否則,是的,您可以簡單地在各自的文件中使用has_and_belongs_to_many :patients
和has_and_belongs_to_many :doctors
。
請特別注意Rails Guide中的第 2.8 節。 這可能需要通讀幾遍,但一旦你明白了,它就會變得有意義,我保證。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.