Rails HABTM与重命名的类关联

时间:2014-03-28 16:41:43

标签: ruby-on-rails activerecord has-and-belongs-to-many

我正在创建一个简单的游戏网站,用户可以在其中创建游戏并邀请其他用户加入他们的游戏。用户既可以是游戏的所有者,也可以是该游戏中的玩家(所有者也必须是玩家)通过:game_players联接表。我希望玩家被称为:player并且游戏的所有者被称为:user。我试图弄清楚如何设置关联。我的问题在以下评论中:

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

我在这里走在正确的轨道上吗?

1 个答案:

答案 0 :(得分:1)

您已走上正轨,但在User课程中,您还应为:game_players设置关联,如下所示:

has_many :game_players

任何时候你有一个has_many,通过:应该是该模型中另一个关联的名称。

是的,您确实需要连接模型上的关联。 Rails需要它们才能使has_many通过工作。

仅供参考,连接表的约定是第一个复数,第二个是单数,所以GamesPlayer(认为占有 - 它是一个游戏的玩家)将是你的连接模型的传统名称