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

时间:2014-04-17 11:28:09

标签: ruby-on-rails

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

rails generate model Match Team:references Team:re
ferences score1:integer score2:integer date:datetime length:integer place:string

我希望 匹配 表包含2个外键(team1,team2),引用 团队上的相同列(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"

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

1 个答案:

答案 0 :(得分:2)

数据库表不能有两个具有相同名称的列。这是您需要的,以使其工作。 (我将使用home_teamaway_team来帮助区分它们,但显然您可以使用team1team2。)

rails g migration AddTeamsToMatch home_team_id:integer away_team_id:integer

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

class AddTeamsToMatch < ActiveRecord::Migration
  def change
    add_column :matches, :home_team_id, :integer
    add_column :matches, :away_team_id, :integer
  end
end

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

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

希望这有帮助。