has_many 通过多个来源 [英] has_many through multiple sources
问题描述
我正在尝试与多个源创建 has_many through
关系.
I am trying to create a has_many through
relation with multiple sources.
例如,一场比赛有一个 home_team
和 away_team
,而一场锦标赛有多个比赛.
For example a game has a home_team
and away_team
and a tournament has multiple games.
使用 has_many through games 关系让所有球队参加锦标赛的最佳方法是什么.
What is the best way to get all teams in the tournament using a has_many through games relation.
现在我的代码是这样的:
Right now my code looks like this:
class Tournament
has_many :teams, :through => :games, :source => :home_team, :uniq => true
end
但我想要某种方式让它表现得像:
but I want some way to make it act like:
class Tournament
has_many :teams, :through => :games, :source => [:home_team, :away_team], :uniq => true
end
多对多关系不是我的问题.假设结构如下,是否有一种好的方法可以让锦标赛中的所有球队都参加.
The many to many relationship is not my problem. Is there a good way to get all the teams in the tournament assuming the structure as follows.
class Game
has_and_belongs_to_many :tournaments
belongs_to :home_team, :class_name => Team, :foreign_key => :home_team_id
belongs_to :away_team, :class_name => Team, :foreign_key => :away_team_id
end
class Tournament
has_and_belongs_to_many :games
end
有没有办法做到Tournament.teams
?
推荐答案
在花了一些时间尝试寻找内置解决方案之后,我最终编写了一个名为游戏中的团队"的自定义查询.它通过 team_1 和 team_2 两次将团队加入游戏,并检查是否有任何游戏 ID 列表在这两个连接中.
After spending some time trying to find a built in solution I just ended up writing a custom query called teams in games. It joins teams to games twice through team_1 and team_2 and checks to see if any of the list of game id's are in either of these two joins.
这个解决方案不是很好,因为它需要多个查询(其中一个只是所有游戏 ID 的一个巨大列表),但我花了很多时间试图想出另一种方法,但没有.至少这种方式有效.
This solution isn't great since it requires multiple queries (One of which is just a huge list of all game ids), but I spent a lot of time trying to come up with another way and couldn't. At least this way works.
我很想学习更好的方法.
I'd love to learn a better way.
游戏内代码:
def self.teams
joined_tables = Team.joins(:home_team).joins(:away_team)
joined_tables.where('games.id in (?) or away_team_games.id in (?)',
select(:id), select(:id)).uniq
end
这篇关于has_many 通过多个来源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!