首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails结合多个多态has_many关联

Rails结合多个多态has_many关联
EN

Stack Overflow用户
提问于 2021-04-15 23:00:08
回答 1查看 89关注 0票数 1

我有一个名为Organization的模型,它有许多teams和许多collaborationsCollaboration也有许多teams。因此,团队模型与OrganizationCollaboration具有多态关联。

我想要做的是organization.teams,这反映了组织中的所有团队和协作中的所有团队(组织的一部分)。

代码语言:javascript
复制
*organizations*
id
user_id
title
...

*collaborations*
id
organization_id
title
...

*teams*
id
teamable_id
teamable_type
title
...

模型

代码语言:javascript
复制
class Organization < ApplicationRecord

  has_many :orgaization_teams, as: :teamable, class_name: "Team"
  has_many :collaboration_teams, through: :collaborations, source: :teams, class_name: "Team"

end

class Collaboration < ApplicationRecord

  belongs_to :organization
  has_many :teams, as: :teamable

end

class Team < ApplicationRecord

  belongs_to :teamable, polymorphic: true
  belongs_to :organization, -> { joins(:teams).where(teams: {teamable_type: 'Organization'}) }, foreign_key: 'teamable_id'
  belongs_to :collaboration, -> { joins(:teams).where(teams: {teamable_type: 'Collaboration'}) }, foreign_key: 'teamable_id'

end

尝试

企图#1

代码语言:javascript
复制
class Organization < ApplicationRecord

  has_many :teams, -> { joins(:organization, :collaboration) }, source: :teamable

end

结果: SystemStackError (堆栈级别太深)

第二次尝试

代码语言:javascript
复制
class Organization < ApplicationRecord

  def teams
    orgaization_teams.or(collaboration_teams)
  end

end

结果: ArgumentError (传递给#或必须在结构上兼容关系)。不兼容的值::联接)

势溶液

我正在考虑将Team上的多态关联分离为organization_idcollaboration_id

所以新的桌子看起来是这样的:

代码语言:javascript
复制
*teams*
id
organization_id
collaboration_id
title
...
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-15 23:28:27

我会用两个分开的外键代替:

代码语言:javascript
复制
class Organization < ApplicationRecord
  has_many :teams
  has_many :collaborations
  has_many :collaboration_teams, 
    through: :collaborations,
    source: :team
end

class Collaboration < ApplicationRecord
  belongs_to :organization
  has_many :teams
end

class Team < ApplicationRecord
  belongs_to :team, optional: true
  belongs_to :organization, optional: true
end

如果希望获得直接属于或组织或其协作的团队,则需要:

代码语言:javascript
复制
Team.where(
  organization_id: org.id
).or(
  Team.where(
    collaboration_id: org.collaborations
  )
)

我不认为这实际上可以写成一个关联,因为它的结构过于复杂。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67116997

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档