Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

has_many through multiple sources

I am trying to create a has_many through relation with multiple sources.

For example a game has a home_team and away_team and a tournament has multiple 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

EDIT: 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

Is there a way to do Tournament.teams?

like image 555
Josh Wilson Avatar asked Mar 08 '13 07:03

Josh Wilson


1 Answers

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.

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.

Code inside of games:

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
like image 111
Josh Wilson Avatar answered Nov 10 '22 05:11

Josh Wilson