Has_many through several sources

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

For example, a game has home_team and away_team , and there are several games in the tournament.

What is the best way to get all the teams in a tournament using the has_many relation through games.

Now my code is as follows:

 class Tournament has_many :teams, :through => :games, :source => :home_team, :uniq => true end 

but I want him to do this:

 class Tournament has_many :teams, :through => :games, :source => [:home_team, :away_team], :uniq => true end 

EDIT: the relationship of many, many is not my problem. Is there a good way to get all the teams in a 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 any way to make Tournament.teams ?

+7
source share
2 answers

After spending some time trying to find a built-in solution, I just wrote my own query, called teams in games. He joins the teams to the games twice through team_1 and team_2 and checks if there is any of the game identifiers in any of these two connections.

This solution is not very large, because it requires several requests (one of which is just a huge list of all game identifiers), but I spent a lot of time trying to come up with a different way and could not. At least that's how it works.

I would like to know the best way.

Code inside the 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 
+4
source

Define such models:

 class Tournament has_many :games has_many :teams, :through => :games end class Game belongs_to :torunament belongs_to :team end class Team has_many :games has_many :tournaments, :through => :games end 

And then call the controller or anywhere:

 tournament.teams 

EDIT:

You can define the scope for this problem in the Tournament model. This is more like some kind of user request, but it is supported by rails out of the box. Or at least I can't remember at that very moment.

You can see how to use them.

http://guides.rubyonrails.org/active_record_querying.html http://apidock.com/rails/ActiveRecord/NamedScope/ClassMethods/scope http://ablogaboutcode.com/2011/02/19/scopes-in-rails- 3 /

You can create a request that will receive all the commands. You can create any request that you like.

-3
source

All Articles