Insert an array of Ruby objects in a Mongo database

1.4k views Asked by At

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!

1

There are 1 answers

2
Rostyslav Diachok On BEST ANSWER

You can simply transform @board.tiles from collection of Objects to collection of ruby Hashes:

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)
  }
})

For more complex thing I recommend you to use mongoid http://mongoid.org/en/mongoid/