Association Help , 2 Teams playing a FootballGame

So I have the models

class FootballGame < ActiveRecord::Base


class Team < ActiveRecord::Base

I want to be able to do something like this

@t1 = Team.create(:name=>"Michigan Wolverines football")
@t2 = Team.create(:name=>"Penn State Nittany Lions football")

@g = FootballGame.create(:hometeam => @t1, :awayteam => @t2)

my migrations:

create_table :football_games do |t|
      t.column :hometeam, :integer
      t.column :awayteam, :integer

create_table :teamsdo |t|
      t.column :name, :integer

I've tried various has_one declarations but I keep ending up with NULL
s for hometeam and awayteam...

Anyone help me ??? Thanks

That's because when you have the foreign key in the FootballGames
table, you need to use belongs_to instead of has_one.

The easiest way is to make the columns hometeam_id and awayteam_id,
and the model becomes

class FootballGame < ActiveRecord::Base
  belongs_to :hometeam, :class_name => "Team"
  belongs_to :awayteam, :class_name => "Team"

If you want to keep your field names hometeam and awayteam in the db,
then you need to add the :foreign_key option to belongs_to.


I was thinking that was only solution but for some reason it seemed
wrong. Guess it is the only baked in method though.

FootballGame belongs to hometeam
FootballGame belongs to awayteam


Thanks Justin