Вопрос

I'm creating a simple game site where users can create games and invite other users to join their games. A User can be both an owner of a Game and a player within that Game (the owner must also be a player) through the :game_players join table. I want the players to be known as :player and the owner of the game to be known as :user. I'm trying to figure out how to set up the associations. My questions are in the comments below:

class User
  has_many :games  # This is the owner association
  has_many :games_playing, class_name: 'Game', through: :game_players  # is this right?
end

class Game
  belongs_to :user  # this is the owner association
  has_many :players, through: :game_players
end

class GamePlayer
  belongs_to :game
  belongs_to :player, class_name: 'User'
  # is this right?  is it necessary?
end

Am I on the right track here?

Это было полезно?

Решение

You're on the right track, but in your User class, you should also set up an association for :game_players, like so:

has_many :game_players

Anytime you have a has_many through, the through: should be the name of another association in that model.

And yes, you do need the associations on the join model. Rails needs them to be present in order to make the has_many through work.

FYI, the convention for join tables is to have the first plural, the second singular, so GamesPlayer (think possessive - it is a game's player) would be the conventional name for your join model.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top