Take the 2-minute tour ×

I have the following models:

class Match < ActiveRecord::Base

has_and_belongs_to_many :teams



class Team < ActiveRecord::Base

has_and_belongs_to_many :matches


They are joined together with a matches_teams table.

It seems I have things set up correctly. I can get @team.matches to work, for instance.

My question is how would I go about assigning two specific teams to a match? In the rails console I can go: @team.match.create and that works, but it creates a new match associated with that team. How do I had another team to that association?

I'm fairly new to Rails if that wasn't already obvious. Thanks!

share|improve this question
I don't think a Match has_and_belongs_to_many :teams, I think a match has a home team and a visitor team. You can completely eliminate the matches_team table using those associations. –  Marc Talbot Feb 8 '12 at 1:08
add comment

1 Answer

up vote 0 down vote accepted

Step by step, if you wanted to add two teams to a match, which I think you want to do:

match = Match.create!(...)
team_one = Team.create!(...)
team_two = Team.create!(...)

match.teams << team_one
match.teams << team_two

Obviously, you can condense this down to fewer lines, but I thought I'd stay explicit here. Furthermore, you could do the same by adding your matches to a team, but that seems a bit less intuitive.

share|improve this answer
add comment

Your Answer


