2014-03-28 45 views
0

我正在创建一个简单的游戏网站,用户可以创建游戏并邀请其他用户加入他们的游戏。用户可以通过:game_players连接表既是游戏的所有者又是该游戏中的玩家(所有者也必须是玩家)。我希望这些球员被称为:player,比赛的主人被称为:user。我试图弄清楚如何设置关联。我的问题在下面的评论中:Rails与改名班HABTM协会

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

你在正确的轨道上,但在你的User类,你也应该成立一个协会:game_players,像这样:

has_many :game_players 

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

是的,你确实需要连接模型上的关联。 Rails需要他们在场,才能让has_many通过工作。

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