使用create时,外键的值为nil

时间:2013-06-19 18:04:46

标签: ruby-on-rails-3

我想创建一个新的Player,并且match_id充满了对类方法的调用: 当我运行这段代码时,match_id会分配一个nil值,而Game就在那里并返回一个合适的Game对象。我在这里做错了什么?

Player.create(game_id: Game.default_game)

“default_game”类方法如下所示:

  def self.default_game
    Game.where(name: "Poker").first
  end

2 个答案:

答案 0 :(得分:1)

如果您的ActiveRecord模型关联设置正确,您可以执行以下操作:

Player.create(game: Game.default_game)

或者,您可以更直接地设置ID:

Player.create(game_id: Game.default_game.id)

答案 1 :(得分:0)

game_id的数据类型是否具有相同的default_game数据类型?在某些语言中,NIL不是崩溃,而是返回值。