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关联更加简单。

发布了30 篇原创文章 · 获赞 10 · 访问量 5262

猜你喜欢

转载自blog.csdn.net/wufeng_no1/article/details/87919519