Ruby on rails 多列关联

Ruby on rails 多列关联,ruby-on-rails,rails-activerecord,Ruby On Rails,Rails Activerecord,假设我有一场足球比赛,两队将参加,一队是主队,一队是客队 因此,在DB中,表匹配我有: home_team_id - integer column away_team_id - integer column 在Match类中,作用域为: belongs_to :team_home, foreign_key: :home_team_id, class_name: 'Team' belongs_to :team_away, foreign_key: :away_team_id, class_nam

假设我有一场足球比赛,两队将参加,一队是主队,一队是客队

因此,在DB中,表匹配我有:

home_team_id - integer column
away_team_id - integer column
在Match类中,作用域为:

belongs_to :team_home, foreign_key: :home_team_id, class_name: 'Team'
belongs_to :team_away, foreign_key: :away_team_id, class_name: 'Team'

哪一个是要放在Team类中的相应关联,以便我可以检索一个团队的所有比赛,包括主客场比赛?

这是一个可能的解决方案

class Team < ActiveRecord::Base

  has_many :home_matches, class_name: "Match", foreign_key: "home_team_id"
  has_many :away_matches, class_name: "Match", foreign_key: "away_team_id"

  def myMatches
    Match.where("home_team_id = ? OR away_team_id = ?", self.id, self.id)
  end

end

class Match  < ActiveRecord::Base
  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

谢谢你,里奇。情况如何?如果有数百万条记录,它将被执行,或者它可能更喜欢一个新的联接表,比如teams\u matches with team\u id和match\u id列2行对应1个匹配?这只是一个可能的解决方案,联接是另一个-在myMatches中,您可以检索一个团队的所有匹配-这就是问题所在