Rails:多对多Model,NoMethodError:未定义的方法

时间:2015-10-20 07:36:24

标签: ruby-on-rails ruby activerecord many-to-many

我暂时坚持这个问题。

这是我的模型关系

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'

1 个答案:

答案 0 :(得分:5)

首先,重新启动您的控制台

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

此外,你确定你的数据库 - 使用rake db:seed

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

  
      
  1. 您正在致电participates(也许您最好称之为participants
  2.   
  3. 您需要确保在关联模型中有数据
  4.   

这就是我要做的事情:

#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等更深层次的问题。