2014-10-29 75 views
0

我是全新的rails,所以這可能是一個微不足道的問題。在閱讀教程時,我已閱讀關於關係標識符has_many和has_many的教程。我似乎無法理解的是它們之間的差異。舉例來說,如果我有3個型號,醫生,約會和患者rails has_many vs has_many through?

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 

我不能只是說,醫生的has_many:患者和患者的has_many:醫生,他們會扯上關係?通過約會來達到這個目的的目的是什麼?

感謝

回答

0

你說得對。如果你說醫生has_many :patients和病人has_many :doctors,那麼他們會有關係。

但是,我認爲本教程的內容是多對多關聯。

如果醫生模型和患者模型被has_many相關的,然後醫生專門擁有病人和病人擁有醫生。但通常情況可能並非如此。醫生可以有很多患者,這些患者不必專屬於醫生;他們可能有其他醫生。

這時候許多一對多協會進來的。在許多到多的關聯,一個對象可以有屬於它但不排除許多對象。這就像醫生模型和患者模型之間的關聯。

有兩種方法可以創建一個許多一對多協會:

  1. has_and_belongs_to_many
  2. has_many#somethingthrough:#joining表

你的情況,您正在使用第二種方式,加入表assocation

查看這個Railscast關於這兩個的詳細解釋。此外,這this official Rails documentation on associations將有所幫助。

0

使用的唯一原因a「到」表是當你想使用包含在中間表中的一些相關數據,在這種情況下,與醫患雙方任命的數據。

此外,has_many預計相關belongs_to,反之亦然,所以你必須使用has_and_belongs_to_many在兩個模型來表示一個多一對多的關係,並創建相應的連接表去用它。

否則,是的,您可以簡單地在其各自的文件中使用has_and_belongs_to_many :patientshas_and_belongs_to_many :doctors

請特別注意Rails Guide中的第2.8節。這可能需要一些通讀,但一旦你得到它,這是有道理的,我保證。