【问题标题】:ActiveRecord::AssociationTypeMismatch: for has_many :through relationshipActiveRecord::AssociationTypeMismatch: for has_many :through 关系
【发布时间】:2015-07-03 17:50:08
【问题描述】:

我正在为一个有很多玩家的游戏建模。玩家还可以玩多个游戏。我有用户、游戏和作为连接表的played_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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    然后你应该可以使用:

    User.first.games << Game.first
    

    【讨论】:

    • 就是这样!非常感谢!
    猜你喜欢
    • 2010-12-13
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    相关资源
    最近更新 更多