定义对另一个表中同一列的两个引用

Pat*_*ryk 3 ruby-on-rails

我的项目中有一个团队表。我已经进行了迁移,应该使用以下命令创建表Match :

rails generate model Match Team:references Team:re
ferences score1:integer score2:integer date:datetime length:integer place:string
Run Code Online (Sandbox Code Playgroud)

我希望我的Matches表包含 2 个外键(team1、team2),引用Teams表上的同一列 (id)。我很确定我做错了,因为在schema.rb中有:

 create_table "matchs", force: true do |t|
    t.integer  "Team_id"
    t.integer  "score1"
    t.integer  "score2"
    t.datetime "date"
    t.integer  "length"
    t.string   "place"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "matchs", ["Team_id"], name: "index_matchs_on_Team_id"
Run Code Online (Sandbox Code Playgroud)

我看不到第二个 Team_id。做我需要的事情的正确方法是什么?

Joe*_*edy 5

数据库表不能有两个同名的列。为了让它发挥作用,您需要这样做。(我将使用home_teamaway_team来帮助区分它们,但显然您可以使用team1team2。)

rails g migration AddTeamsToMatch home_team_id:integer away_team_id:integer
Run Code Online (Sandbox Code Playgroud)

这将生成如下所示的迁移:

class AddTeamsToMatch < ActiveRecord::Migration
  def change
    add_column :matches, :home_team_id, :integer
    add_column :matches, :away_team_id, :integer
  end
end
Run Code Online (Sandbox Code Playgroud)

然后在您的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"

  # Get all matches
  def matches
    self.home_matches + self.away_matches
  end
end
Run Code Online (Sandbox Code Playgroud)

在您的Match模型中,您可以:

class Match < ActiveRecord::Base
  belongs_to :home_team, class_name: "Team"
  belongs_to :away_team, class_name: "Team"

  # List both teams as array
  def teams
    [self.home_team, self.away_team]
  end
end
Run Code Online (Sandbox Code Playgroud)

希望这有帮助。