has_many通过多个来源

我试图has_many through与多个来源的关系创建一个has_many through

例如,游戏具有home_teamaway_team并且锦标赛具有多个游戏。

使用has_many游戏关系让锦标赛中所有球队参赛的最佳方式是什么?

现在我的代码看起来像这样:

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

但我想要一些方法让它像:

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

编辑:多对多的关系不是我的问题。 是否有一个很好的方法让比赛中的所有球队都采用如下结构。

 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的任何列表是否属于这两个联接中的任何一个。

这个解决方案并不是很好,因为它需要多个查询(其中一个只是所有游戏ID的巨大列表),但我花了很多时间试图想出另一种方式而不能。 至少这种方式有效。

我想学习更好的方法。

游戏内部代码:

 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 

定义这样的模型:

 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 

然后调用控制器,或者在任何地方:

 tournament.teams 

编辑:

您可以在Tournament模型中定义此类问题的scope 。 这更像是一些自定义查询,而是由开箱即用的rails支持。 或者至少在这个时刻我不记得了。

你可以看看如何使用它们。

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 /

您可以构建一个可以获得所有团队的查询。 您可以创建任何您喜欢的查询。