0

So, I'm using the Ruby MongoDB driver and I want to insert and object like this:

 db.insert_one({
  'game_id' => @token,
  'board' => {
    'tiles' => @board.tiles
  }
})

where @board is an instance of a Board class.

class Board
 attr_accessor :tiles
  def initialize()
    @tiles = [Tile.new, Tile.new]
  end
end

and Tile

class Tile
  def initialize()
    @x = 1, @y = 1
  end
  def to_json(options)
    {"x" => @x, "y" => @y}.to_json
  end
end

So at the end, 'tiles' field should look like this:

'tiles': [{x:1, y:1}, {x:1, y:1}]

I'm getting this error:

undefined method `bson_type' for #<Tile:0x007ff7148d2440>

The gems I'm using: 'sinatra', 'mongo (2.0.4)' and 'bson_ext' (all required using Bundler.require). Thanks!

4

1 回答 1

2

您可以简单地将 @board.tiles 从 collection ofObjects转换为 collection of rubyHashes​​ :

class Tile
  def initialize()
    @x = 1, @y = 1
  end
  def raw_data
    {"x" => @x, "y" => @y}
  end
end

db.insert_one({
  'game_id' => @token,
  'board' => {
    'tiles' => @board.tiles.map(&:raw_data)
  }
})

对于更复杂的事情,我建议您使用 mongoid http://mongoid.org/en/mongoid/

于 2015-06-11T00:18:40.170 回答