也許你可以找到這個一點點有用:
遷移遊戲:
移民團隊:
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">]
你可以定義一個方法遊戲模型中的'teams'並返回數組中的away_team和home_team。 – Mindbreaker
我可以在控制檯中使用此方法調用遊戲記錄嗎? – 2bor02b