Mongoid - 如何使用嵌入文档创建文档?

时间:2013-04-10 21:29:23

标签: ruby-on-rails mongoid

我目前正在使用Mongoid开发一个Rails项目。我定义了Game模型,它嵌入了许多GamePlayers。不幸的是,我无法弄清楚如何创建新游戏。我可以使用Game.create创建一个没有玩家的游戏,但是当我尝试为游戏创建玩家时,它会产生语法错误。我尝试过在网上搜索,但我找不到任何与问题相关的内容。

以下是GamesController中我尝试过的创建代码。

  def new
    @game = Game.create(
        epoch: 1,    
        turn: 0,
        auction_turn: -1,
        auction_type: -1,
        sun: 1,
        ras: 0,
        auction_track: []

        game_players: [ #doesn't work
          { suns:[9,6,5,2]
          }        
        ]      
    )

    redirect_to :action => "show", :id => @game._id
  end

产生错误

/home/<redacted>/Ra/ra_server/app/controllers/games_controller.rb:36: syntax error, unexpected tIDENTIFIER, expecting ')'
        game_players: [ #doesn't work

以下是我的模特

class Game
  include Mongoid::Document

  field :epoch, type:Integer
  field :turn, type:Integer
  field :auction_turn, type:Integer
  field :auction_type, type:Integer
  field :sun, type:Integer
  field :ras, type:Integer
  field :auction_track, type:Array


  embeds_many :game_players 
end

class GamePlayer
  include Mongoid::Document

  field :score, type:Integer
  field :bid, type:Integer
  field :suns, type:Array
  field :next_suns, type:Array
  field :pharaohs, type:Integer
  field :niles, type:Integer
  field :floods, type:Integer
  field :gods, type:Integer
  field :gold, type:Integer
  field :civilizations, type:Array
  field :monuments, type:Array

  embedded_in :game
end

1 个答案:

答案 0 :(得分:1)

您的参数中的auction_track:[]后面显示您缺少逗号。