我有一个超级简单的问题,但我哪里也找不到答案!
问题:
如果我以前有这样的has_many关系:has_many :wikis,如果以后通过如下的关系创建has_many,我会保留这种关系吗?
has_many :collaborators
has_many :wikis, through: :collaborators这些都在我的用户模型中。
背景:
在我的rails应用程序中,我有一个用户模型和一个Wiki模型。我只是赋予用户在私有wiki上协作的能力,所以我迁移了一个协作者模型,然后通过关系创建了has_many。我不确定在放置has_many :wikis之后是否还需要has_many :wikis, through: :collaborators。
我感到困惑的原因是,用户应该仍然是,能够在没有协作者的情况下创建wiki,而且我不确定has_many through关系是如何工作的。
最初我只有用户和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发布于 2018-03-11 03:35:35
当has_many通过has_many存在时,has_many仍然是必要的吗?
当has_many像您的模型一样存在has_many through时,不需要使用
has_many :wikis # should I delete this?
has_many :collaborators
has_many :wikis, through: :collaborators我应该删除这个吗?
是的,你可以删除这个,你不需要这个作为同一个belongs_to
来自 Association
has_many关联表示与另一个模型的一对多连接.您经常会在belongs_to关联的“另一面”找到这种关联。此关联表示模型的每个实例都有另一个模型的零个或多个实例。例如,在包含作者和书籍的应用程序中,可以这样声明作者模型:

来自 Association
has_many :through关联通常用于建立与另一个模型的多到多连接。此关联表明,通过第三个模型,声明模型可以与另一个模型的零个或多个实例相匹配。例如,考虑一种医疗实践,病人预约去看医生。相关的关联声明可以如下所示: 类内科医生< ApplicationRecord has_many :约会has_many :患者,通过::约会结束级任命< ApplicationRecord belongs_to :内科医生belongs_to :病人末级病人< ApplicationRecord has_many :预约has_many :内科医生,通过::

您可以只使用没有has_many的has_many :through关联,但这是一对多的,而不是多对多的。
has_many协会(没有has_many :through)是与另一个模型的一对多连接。has_many :through协会与另一种模式建立了多到多的连接。更新
看,一个医生可能有很多病人,另一方面,一个病人可能有很多医生,如果你对病人使用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
...
endhttps://stackoverflow.com/questions/49215823
复制相似问题