Rails: many to many Model, NoMethodError: undefined method

Rails: many to many Model, NoMethodError: undefined method

我被这个问题卡住了一段时间。

这是我的模型关系

class Game < ActiveRecord::Base
    has_many :participates , :dependent => :destroy
    has_many :players, through: :participates, :dependent => :destroy
end

class Player < ActiveRecord::Base
    has_many :participates , :dependent => :destroy
    has_many :games, through: :participates, :dependent => :destroy
end

class Participate < ActiveRecord::Base
  belongs_to :player
  belongs_to :game
end

我把它放在 seed.rb

Player.destroy_all
Game.destroy_all
g1 = Game.create(game_name: "LOL")
g2 = Game.create(game_name: "DOTA")
p1 = Player.create(player_name: "Coda", games: [g1,g2]);
p2 = Player.create(player_name: "Nance", games: [g2]);

当我使用 rails console 时,模型 Participate 工作正常。 它可以相对地找到gameplayer,但是下面的命令会抛出错误。

[53] pry(main)> Game.first.players
  Game Load (0.4ms)  SELECT  `games`.* FROM `games`  ORDER BY `games`.`id` ASC LIMIT 1
    NoMethodError: undefined method `players' for #<Game:0x007fd0ff0ab7c0>
    from /Users/Coda/.rvm/gems/ruby-2.1.3@rails416/gems/activemodel-4.2.3/lib/active_model/attribute_methods.rb:433:in `method_missing'


[56] pry(main)> Player.first.games
      Player Load (0.4ms)  SELECT  `players`.* FROM `players`  ORDER BY `players`.`id` ASC LIMIT 1
    NoMethodError: undefined method `games' for #<Player:0x007fd0fd8a7cf0>
    from /Users/Coda/.rvm/gems/ruby-2.1.3@rails416/gems/activemodel-4.2.3/lib/active_model/attribute_methods.rb:433:in `method_missing'

首先,重启你的主机

如果您在控制台中 运行 时更改了任何模型/代码,它只会在您重新启动时再次运行。

另外,你确定你的数据库是用rake db:seed播种的吗?


你的代码看起来没问题;我认为这是一个问题的两个原因如下:

  1. You're calling participates (maybe you'd be better calling it participants)
  2. You need to make sure you have data in your associative models

我会这样做:

#app/models/game.rb
class Game < ActiveRecord::Base
   has_many :participants
   has_many :players, through: :participants
end

#app/models/participant.rb
class Participant < ActiveRecord::Base
   belongs_to :game
   belongs_to :player
end

#app/models/player.rb
class Player < ActiveRecord::Base
   has_many :participations, class_name: "Participant"
   has_many :games, through: :participations
end

应该避免任何潜在的命名错误。


接下来,您需要确保模型中有数据。

我已经使用了 many-to-many 很多次;每次我发现您需要关联模型中的数据才能工作。

$ rails c
$ g = Game.first
$ g.players

如果此没有输出任何集合数据,则意味着您的关联要么是空的,要么是错误的。

这可能是您遇到问题的原因,但老实说,我不知道。为确保它有效,您可能希望直接填充Participant

$ rails c
$ g = Game.first
$ p = Player.first
$ new_participation = Participant.create(player: p, game: g)

如果这个不起作用,这可能是 ActiveRecord 等更深层次的问题。