多列关联

时间:2018-10-06 09:40:06

标签: ruby-on-rails rails-activerecord

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

因此,在DB中,表“ matches”具有:

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'

哪个是科恩协会才能加入“团队”类,这样我就可以检索一个团队的所有比赛,而这两个主场都没有比赛?

1 个答案:

答案 0 :(得分:1)

这是一种可能的解决方案

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