Ruby on Rails——Active Records 關聯

Rails 支持六種關聯:

  • belongs_to
  • has_one
  • has_many
  • has_many :through
  • has_one :through
  • has_and_belongs_to_many

1.belongs_to 聲明所在的模型實例屬於另一個模型的實例。 在belongs_to關聯聲明中必須使用單數形式。

2.has_one 表示該模型的實例包含或擁有另一個模型的一個實例。

3.has_many 建立兩個模型之間的一對多關係,在belongs_to管理的對應面經常使用這個關聯。

4.has_many :through 用於建立兩個模型的多對多關聯,表示一個模型的實例可以藉由第三個模型,擁有零個或多個另一個模型的實例。例如,在醫療領域,病人要和醫生約定康復鍛鍊時間,關聯聲明如下:

class Physician < ApplicationRecord

  has_many :appointments

  has_many :patients, through: :appointments

end

 

class Appointment < ApplicationRecord

  belongs_to :physician

  belongs_to :patient

end

 

class Patient < ApplicationRecord

  has_many :appointments

  has_many :physicians, through: :appointments

end

has_many :through還可以簡化嵌套的has_many關聯。

5.has_one :through 用於建立兩個模型的一對一關聯,表示一個模型的實例可以藉由第三個模型,擁有一個另一模型的實例。

6.has_and_belongs_to_many 直接建立兩個模型的多對多關聯。

通過上面的介紹我們發現,其實belongs_to和has_one是一種對應關係,可以選擇使用一種;has_many :through和has_and_belongs_to_many則可以實現相同的功能,我們也可以選擇使用其中一種。那麼我們應該如何選擇呢?

關於has_one和belongs_to我們主要還是考慮語意,他在數據庫中的區別就是外鍵會存放在哪一個表中(外鍵會存放在belongs_to模型對應的表中)。

而關於has_many :through和has_and_belongs_to_many,根據經驗,如果想把關聯模型當作獨立實體使用,要用has_many :through關聯;如果不需要使用關聯模型,那麼建立has_and_belongs_to_many關聯更加簡單。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章