简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM