Association Help , 2 Teams playing a FootballGame

So I have the models

class FootballGame < ActiveRecord::Base
end

and

class Team < ActiveRecord::Base
end

I want to be able to do something like this

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

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

my migrations:

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

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

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

Anyone help me ??? Thanks

On 10/15/07, macarthy [email protected] wrote:

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”
end

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.

Pat

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

hmmm…

Thanks Justin

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs