Has and belongs to many

Hello, I’ve searched but I can’t find a good tutorial to has and
belongs to many.

What should both of my models, Games and Players, look like if a game
has many players and a player has many games.

Also when I create I want to be able to associate the player with the
game. Before I was doing
@game.save
for player in @home.players
player.game_id = @game
player.increment! :games
end

What should I do now to make the association? Also how do I find all
players by game_id?

Doing player.game_ids = @game gives
undefined method `reject’ for 1:Fixnum

Also why is increment! not working.
By the way @home = Team.find_by_user_id(current_user.id)
and team has many players.

So if I have a Game a Player and a Team I would want to do
Game has many teams (actually only 2)
Team has many games
all through a Player???

Hello, I’ve searched but I can’t find a good tutorial to has and
belongs to many.

What should both of my models, Games and Players, look like if a game
has many players and a player has many games.

http://mboffin.com/stuff/ruby-on-rails-data-relationships.png

On Apr 7, 2:48 pm, edberner [email protected] wrote:

What should both of my models, Games and Players, look like if a game
has many players and a player has many games.

The key is, a game is a connection between two teams. So a Games
table would consist of three columns: id, home_team_id, away_team_id:

class Game
belongs_to :home_team, :class_name => “Team”
belongs_to :away_team, :class_name => “Team”
end

class Player
belongs_to :team
end

class Team
has_many :games
has_many :players
end

For example:

cubs = Team.find(1)
sox = Team.find(2)

g = Game.create(:home_team => cubs, :away_team => sox)

g.home_team.players # shows players on the Cubs

p = cubs.players.first
p.team.games # shows all the games this player is in

Of course, that last bit assumes the player plays in every game the
team plays in. If that’s not the case for you, you would need to add
another table to tracks ‘attendance’ of the player for each game.

So I’ve just shown the simple case here, in the hopes it gives you a
start in the right direction or is at least food for thought.

Jeff