Jonathon Doesen
Jonathon Doesen

Reputation: 563

How to create a relationship between two objects in Rails has_many_and_belongs_to_many relationship

I have the following models:

class Match < ActiveRecord::Base

has_and_belongs_to_many :teams

end 

And

class Team < ActiveRecord::Base

has_and_belongs_to_many :matches

end

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!

Upvotes: 2

Views: 1054

Answers (1)

miked
miked

Reputation: 4499

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.

Upvotes: 1

Related Questions