Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving binary data using MongoID in Rails

This seems like it should be straightforward and work. MongoDB / BSON have a native binary type, and the Moped driver supports it. But when I try to create a scaffold in my rails project

rails g scaffold image png:binary source:string

I get this model:

class Image
  include Mongoid::Document
  field :png, type: Binary
  field :source, type: String
end

which generates this error:

uninitialized constant Image::Binary

Using Rails 3.2.8 and Mongoid 3.0.9.

like image 712
Leopd Avatar asked Sep 19 '25 13:09

Leopd


1 Answers

You will need to use the Moped::BSON::Binary type:

class Image
  ...
   # mongoid version <= v3 
  field :png, type: Moped::BSON::Binary
   # mongoid version >= v4 
  field :png, type: BSON::Binary
end


i = Image.new
# mongoid version <= v3 
i.png = Moped::BSON::Binary.new(:generic, <image data> ) 

# mongoid version >= v4 
i.png = BSON::Binary.new(:generic, <image data> ) 
like image 146
ndbroadbent Avatar answered Sep 21 '25 04:09

ndbroadbent