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

我的项目中有一个Team表。 我做了一个应该使用以下命令创建表Match的迁移:

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

我希望我的Matches表包含2个在Teams表上引用相同列(id)的外键(team1,team2)。 我很确定我做错了,因为在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。 做我需要的正确方法是什么?

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

 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 

希望这会有所帮助。