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

这是我的 模型关系

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 播种了你的数据库 吗?

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



这是我要做的:

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

关于ruby-on-rails - Rails : many to many Model, NoMethodError:未定义的方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33230669/

10-11 05:27