Rails: bi-directional has_many :through relationship
Posted
by Chris
on Stack Overflow
See other posts from Stack Overflow
or by Chris
Published on 2010-05-24T14:40:01Z
Indexed on
2010/05/24
14:41 UTC
Read the original article
Hit count: 162
ruby-on-rails
|has-many-through
I have three models in a Rails application: Game
represents an instance of a game being played. Player
represents an instance of a participant in a game. User
represents a registered person who can participate in games.
Each Game
can have many Players
, and each User
can have many Players
(a single person can participate in multiple games at once); but each Player
is in precisely one Game
, and represents precisely one User
. Hence, my relationships are as follows at present.
class Game
has_many :players
end
class User
has_many :players
end
class Player
belongs_to :game
belongs_to :user
end
... where naturally the players
table has game_id
and user_id
columns, but games
and users
have no foreign keys.
I would also like to represent the fact that each Game
has many Users
playing in it; and each User
has many Games
in which they are playing. How do I do this? Is it enough to add
class Game
has_many :users, :through => :players
end
class User
has_many :games, :through => :players
end
© Stack Overflow or respective owner