2014-04-17 103 views
0

有一个团队表在我的项目中。 我做了应该使用下面的命令来创建表匹配迁移:定义两个引用到另一个表中的同一列

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。 什么是正确的方式来做我所需要的?

+0

同一个表的两个'外键'?这怎么可能? – Pavan

+0

为什么这不可能? – Patryk

+0

你不能有两个'team_id's.Pubably你可以有'team_1_id'和'team_2_id'。 – Pavan

回答

1

数据库表不能有两个同名的列。这是你需要的,以使其发挥作用。 (我要使用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 

希望这有助于。

相关问题