Rails:获取一个associations关联

Rails: Get an associations association

假设我有以下联想:

class Player
  has_many :team_members
  has_many :teams, through: :team_members, dependent: :destroy

  has_many :invites, class_name: 'Invitation', as: :invitee
end

class Team
  has_many :team_members
  has_many :players, through: :team_members, dependent: :destroy

  has_many :invites, class_name: 'Invitation', as: 'invitee' 
  has_many :invitations, as: :inviter
end

class Invitation
  belongs_to :inviter, polymorphic: true, optional: true
  belongs_to :invitee, polymorphic: true, optional: true
end

基本上,TeamPlayer 都可以被邀请参加游戏,而 Player 创建并拥有一个团队。因此,当 Player 登录时,我想显示 Player 收到的邀请以及 Player 拥有的任何 Team 收到的任何邀请。

我正在寻找类似的东西:

player = Player.first
player.invites << player.teams.invites

但我无法执行上述操作,因为 player.teams.invites return 是类型不匹配,因为它 return 是 Team 而不是 Invitation

有什么有效的方法可以return一个关联和一个关联查询最少的关联?我知道我可以写一个循环,但我想知道是否有更优雅的东西。

如果我是你,我想我会做这样的事情:

class Invitation
  belongs_to :inviter, polymorphic: true, optional: true
  belongs_to :invitee, polymorphic: true, optional: true

  class << self

    def for_teams(teams)
      where(invitee_type: 'Team', invitee_id: teams) 
    end

  end

end

然后,您可以执行以下操作:

Invitation.for_teams(player.teams)

并取回任何球队收到的所有邀请,其中球队有该球员作为成员。

顺便说一句,我认为您的 invites 联想是错误的。我相信他们应该是:

class Team
  has_many :team_members
  has_many :players, through: :team_members, dependent: :destroy
  has_many :invites, class_name: 'Invitation', as: :invitee
  has_many :invitations, as: :inviter
end

class Player
  has_many :team_members
  has_many :teams, through: :team_members, dependent: :destroy
  has_many :invites, class_name: 'Invitation', as: :invitee
end

如您所见,您可能会得到不正确的结果,因为您忽略了 has_many 调用中的 invitee_type