ActiveRecord :: AssociationTypeMismatch:for has_many:through relationship

时间:2015-04-24 23:21:04

标签: ruby-on-rails ruby activerecord has-many-through has-many

我正在为一个有很多玩家的游戏建模。玩家还可以玩多个游戏。我有用户,游戏和plays_game作为联接表。

这是我第一次涉足has_many:通过关系,所以我希望这是一个简单的问题。或者至少是一个简单分辨率的问题。

class User < ActiveRecord::Base
   has_many :played_games
   has_many :games, :through => :played_games  
end

class Game < ActiveRecord::Base
   has_many :played_games
   has_many :users, :through => :played_games
end

class PlayedGame < ActiveRecord::Base
  belongs_to :users
  belongs_to :games
end

当我尝试将游戏添加到用户(来自控制台)时会发生这种情况:

User.first.played_games << Game.first

结果:

ActiveRecord::AssociationTypeMismatch: PlayedGame(#70279902258580) expected, got Game(#70279901145600)

好吧,也许我误会了。也许我应该尝试添加games

User.first.games << Game.first.id

结果:

NameError: uninitialized constant User::Games

感谢任何文档的帮助或链接。提前谢谢!

1 个答案:

答案 0 :(得分:1)

问题似乎是您已将belongs_to上的PlayedGame关联错误地定义为复数,因为它们应该是单数。将它们更改为:

class PlayedGame < ActiveRecord::Base
  belongs_to :user
  belongs_to :game
end

然后你应该可以使用:

User.first.games << Game.first