Search code examples
ruby-on-railsrubyactiverecordhas-many-throughhas-many

ActiveRecord::AssociationTypeMismatch: for has_many :through relationship


I am modeling a game which has many players. Players can also play multiple games. I have users, games and played_game which is acting as the join table.

This is my first foray into has_many :through relationships so I'm hopeful that this is a simple question. Or at least a question with a simple resolution.

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

This is what happens when I try to add a game to a user (from console):

User.first.played_games << Game.first

Results in:

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

Ok, maybe I'm misunderstanding. Perhaps it's games that I should try to add to:

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

Results in:

NameError: uninitialized constant User::Games

Any help or link to documentation is appreciated. Thanks in advance!


Solution

  • The problem appears to be that you've defined the belongs_to associations on PlayedGame incorrectly as plural when they should be singular. Change them to:

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

    And then you should be able to use:

    User.first.games << Game.first