Hi Torsten,
I am not sure I entire understand your situation, but if I were you
this is how I might set it up:
First, I would have a table teams, a table matches, and a join-table
called matches_teams
.script/generate scaffold Team
.script/generate scaffold Match
.script/generate migration create_matches_teams match_id:integer
team_id:integer
so for your migration for your teams table
001_create_teams
create_table :teams, :force => true do |t|
t.string :name
t.timestamps
end
002_create_matches
create_table :matches, :force => true do |t|
t.datetime :kickoff
t.timestamps
end
003_create_matches_teams
create_table :matches_teams, :id => false, :force => true do |t|
t.integer match_id
t.integer :team_id
end
Now you need to set up your associations in your models so that
ActiveRecord can build proper queries
teams.rb
has_and_belongs_to_many :matches
matches.rb
has_and_belongs_to_many :teams
Now, you can open up the Rails console using the command
.script/console (or script/console sandbox for sandbox mode) and play
around with the associations
>> team1 = Team.create(:name => 'Mercenaries')
>> ... output ...
>> team2 = Team.create(:name => 'Matadors')
>> ... output ...
>> match1 = Match.create(:kickoff => Time.now)
>> ... output ...
>> match1 << team1
>> ... output...
>> match1 << team2
>> .. output ...
>> match1.teams
>> should return an array of teams associated with this match.
Now I haven't tried any of this code above, but this is how HABTM
table associations work. If you never need to have a join table with
additional attributes consider using :through => :table_name
associations, they are more rich.
I hope this helps!
- Mike
--- In RubyOnRails@yahoogroups.com, "Torsten Mangner" <tmangner@...>
wrote:
>
> hi there,
>
> i got to tables "teams" and "matches".
>
> create_table :teams do |t|
> t.string :name
> t.timestamps
> end
>
> create_table :matches do |t|
> t.datetime :kickoff
> t.timestamps
> end
>
> i have to reference two teams (home & away) in the matches table. but
> i dont know how to do it.
>
> when i do something like this:
>
> t.column 'home_team_id', :integer
> t.column 'away_team_id', :integer
>
> then i loose the association to the teams-table.
>
> anyone with a tip for me? any help is highly appreciated.
>