2014-04-17 24 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 

希望這有助於。

相關問題