天天看點

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關聯更加簡單。