has_many through 存在时还需要 has_many 吗?

Is has_many still necessary when has_many through exists?

我觉得这是一个超级简单的问题,但我找不到任何答案!

问题:

如果我以前有这样的 has_many 关系:has_many :wikis,如果以后我通过如下关系创建 has_many,我是否保持这种关系?

has_many :collaborators
has_many :wikis, through: :collaborators

这些都在我的用户模型中。

背景:

在我的 rails 应用程序中,我有一个 User 模型和一个 Wiki 模型。我只是让用户能够在私人 wiki 上进行协作,所以我迁移了一个 Collaborator 模型,然后通过关系来创建 has_many。我不确定在输入 has_many :wikis, through: :collaborators.

后是否还需要 has_many :wikis

我感到困惑的原因是因为用户应该仍然 能够在没有协作者的情况下创建 wiki,我不确定 has_many through 关系在幕后如何运作.

原来我只有一对多关系的User和Wiki。

# User model
class User < ApplicationRecord
  ...    
  has_many :wikis # should I delete this?
  has_many :collaborators
  has_many :wikis, through: :collaborators
  ...
end

# Collaborator model
class Collaborator < ApplicationRecord
  belongs_to :user
  belongs_to :wiki
end

# Wiki model
class Wiki < ApplicationRecord
  belongs_to :user

  has_many :collaborators, dependent: :destroy
  has_many :users, through: :collaborators
  ...
end

Is has_many still necessary when has_many through exists?

has_many 不需要 has_many through 像你的模特

has_many :wikis # should I delete this?
has_many :collaborators
has_many :wikis, through: :collaborators

should I delete this?

是的,你可以删除这个,你不需要这个一样belongs_to

The has_many Association

has_many 关联表示与另一个模型的 one-to-many 关联。您经常会在 belongs_to 关联的 "other side" 上找到此关联。此关联表示模型的每个实例都具有另一个模型的零个或多个实例。例如,在包含作者和书籍的应用程序中,作者模型可以这样声明:

The has_many :through Association

has_many :through 关联通常用于与另一个模型建立 many-to-many 连接。此关联表明声明模型可以通过第三个模型与另一个模型的零个或多个实例匹配。例如,考虑患者预约看医生的医疗实践。相关的关联声明可能如下所示:

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 关联而不使用 has_many :through,但这是 one-to-many,而不是 many-to-many

  • has_many 协会(没有 has_many :through)是 one-to-many 与另一个模型的联系
  • has_many :through 关联建立了与另一个模型的 many-to-many 连接

更新

你看,一个医生可能有很多病人,另一方面,一个病人可能有很多医生,如果你使用 has_many 关联而不通过病人,那么这称为 one-to-many 关联,这意味着一个医生有很多病人,另一方面,一个病人属于一个医生,现在关联看起来像这样

class Physician < ApplicationRecord
  has_many :patients
end

class Patient < ApplicationRecord
  belongs_to :physician
end

更新 2

has_many通过标准格式编辑后的模型

# User model
class User < ApplicationRecord
  ...    
  has_many :collaborators
  has_many :wikis, through: :collaborators
  ...
end

# Collaborator model
class Collaborator < ApplicationRecord
  belongs_to :user
  belongs_to :wiki
end

# Wiki model
class Wiki < ApplicationRecord
  has_many :collaborators, dependent: :destroy
  has_many :users, through: :collaborators
  ...
end