Question

I'm working on Rails4, Mongoid4 and Gridfs. I;m not able to connect gridfs filesystem

class GridfsController < ApplicationController
  def serve
    gridfs_path = env["PATH_INFO"].gsub("/uploads/", "")
    begin
     gridfs_file = Mongo::GridFileSystem.new(Mongo::DB.new('database_name', Mongo::Connection.new('localhost'))).open(gridfs_path, 'r')
    self.response_body = gridfs_file.read
    self.content_type = gridfs_file.content_type
   rescue Exception => e
    self.status = :file_not_found
    self.content_type = 'text/plain'
    self.response_body = ''
    raise e
  end
 end
end

Getting this error

NameError (uninitialized constant GridfsController::Mongo):
app/controllers/gridfs_controller.rb:7:in `serve'

Was it helpful?

Solution

Mongoid doesn't use the "official" Ruby driver to talk to MongoDB and that's where Mongo::GridFileSystem comes from. Mongoid uses Moped to talk to MongoDB and Moped doesn't know anything about GridFS.

AFAIK the usual GridFS solution is to use mongoid-grid_fs to talk to GridFS:

self.response_body = Mongoid::GridFs[gridfs_path].data

or if you have the id instead of the path:

self.response_body = Mongoid::GridFs.get(gridfs_id).data

OTHER TIPS

There is an implementation of the gridfs specs for the Moped driver here: moped-gridfs

It's better than loading two drivers (moped and mongo-ruby-driver)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top