0

我的遊戲模型home_team_id和away_team_id有兩個字段。Rails - 將一個模型中的兩個不同字段關聯爲一個關聯

我想將這兩個領域作爲與遊戲相關的團隊。

這些團隊可以屬於一個以上的比賽,我有我的團隊模式

has_many :games 

我不知道要放什麼東西在我的遊戲模式。

has_many :teams 

不起作用,因爲它不知道找home_team_id和away_team_id。有沒有辦法告訴它,團隊有兩個不同的鑰匙?

我也試過這個,但它也不起作用。

has_one :away_team, :class_name => 'Team', :foreign_key => 'id' 
has_one :home_team, :class_name => 'Team', :foreign_key => 'id' 

最後我只想在控制檯中運行@ game.teams並讓主隊和客隊返回。

+0

你可以定義一個方法遊戲模型中的'teams'並返回數組中的away_team和home_team。 – Mindbreaker

+0

我可以在控制檯中使用此方法調用遊戲記錄嗎? – 2bor02b

回答

3

假設你已經創建了喜歡你的遊戲遷移:

class CreateGames < ActiveRecord::Migration 
    def change 
    create_table :games do |t| 
     t.integer :home_team_id 
     t.integer :away_team_id 

     t.timestamps 
    end 
    end 
end 

您可以通過指定喜歡你的模型歸檔

class Game < ActiveRecord::Base 
    belongs_to :away_team, class_name: 'Team', foreign_key: 'away_team_id' 
    belongs_to :home_team, class_name: 'Team', foreign_key: 'home_team_id' 

    def teams 
    [away_team, home_team] 
    end 
end 
+0

這工作完美。儘可能簡單,我也希望,謝謝! – 2bor02b

1

也許你可以找到這個一點點有用:

遷移遊戲:

移民團隊:

class CreateTeams < ActiveRecord::Migration 
    def change 
    create_table :teams do |t| 
     t.string :name 

     t.timestamps 
    end 
    end 
end 

型號Game

class Game < ActiveRecord::Base 
    belongs_to :home_team, :class_name => "Team" 
    belongs_to :away_team, :class_name => "Team" 

    # helper for teams 
    def teams 
    [home_team, away_team] 
    end 
end 

添加引用

class AddReferences < ActiveRecord::Migration 
    def change 
    change_table :games do |t| 
     t.integer :home_team_id 
     t.integer :away_team_id 
    end 
    end 
end 

在控制檯:

Team.new(name: 'foo').save 

Team.new(name: 'bar').save 

Game.new(home_team: Team.first, away_team: Team.last).save 

Game.first 
# => #<Game id: 1, match_date: nil, created_at: "2013-11-20 21:53:41", updated_at: "2013-11-20 21:53:41", home_team_id: 1, away_team_id: 6> 

Game.first.teams 
# => [#<Team id: 1, name: "foo", created_at: "2013-11-20 21:40:19", updated_at: "2013-11-20 21:40:19">, #<Team id: 2, name: "bar", created_at: "2013-11-20 21:53:12", updated_at: "2013-11-20 21:53:12">] 
+0

這起作用。我的關聯需要是belongs_to,我需要定義隊列數組。謝謝。 – 2bor02b

相關問題