我有一个名为Organization的模型,它有许多teams和许多collaborations。Collaboration也有许多teams。因此,团队模型与Organization和Collaboration具有多态关联。
我想要做的是organization.teams,这反映了组织中的所有团队和协作中的所有团队(组织的一部分)。
表
*organizations*
id
user_id
title
...
*collaborations*
id
organization_id
title
...
*teams*
id
teamable_id
teamable_type
title
...模型
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
class Organization < ApplicationRecord
has_many :teams, -> { joins(:organization, :collaboration) }, source: :teamable
end结果: SystemStackError (堆栈级别太深)
第二次尝试
class Organization < ApplicationRecord
def teams
orgaization_teams.or(collaboration_teams)
end
end结果: ArgumentError (传递给#或必须在结构上兼容关系)。不兼容的值::联接)
势溶液
我正在考虑将Team上的多态关联分离为organization_id和collaboration_id
所以新的桌子看起来是这样的:
*teams*
id
organization_id
collaboration_id
title
...发布于 2021-04-15 23:28:27
我会用两个分开的外键代替:
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如果希望获得直接属于或组织或其协作的团队,则需要:
Team.where(
organization_id: org.id
).or(
Team.where(
collaboration_id: org.collaborations
)
)我不认为这实际上可以写成一个关联,因为它的结构过于复杂。
https://stackoverflow.com/questions/67116997
复制相似问题