简体   繁体   English

Rails HABTM与重命名类的关联

[英]Rails HABTM association with renamed classes

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. 通过:game_players连接表,用户既可以是游戏的所有者,也可以是该游戏内的玩家(所有者也必须是玩家)。 I want the players to be known as :player and the owner of the game to be known as :user . 我希望玩家被称为:player ,游戏所有者被称为: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: 您的方向正确,但在User类中,还应该为:game_players建立关联, :game_players

has_many :game_players

Anytime you have a has_many through, the through: should be the name of another association in that model. 每当您有has_many通过时,through:应该是该模型中另一个关联的名称。

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. Rails需要存在它们,以使has_many通过工作。

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. 仅供参考, GamesPlayer表的约定是具有第一个复数和第二个单数,因此GamesPlayer (认为​​所有格-它是游戏的玩家)将是您的GamesPlayer模型的常规名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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