rails mongoid + carrierwave

中间插件:gem 'carrierwave-mongoid' 

使用MongoDB's GridFS存储文件。

 

1、在Gemefile文件中添加carrierwave-mongoid

        gem 'mongoid'

        gem 'mongoid-grid_fs'

        gem 'carrierwave'

        gem 'carrierwave-mongoid'

        gem 'mini_magick'

 

2、创建carrierwave的配置文件config/initializers/carrierwave.rb。

#> config/initializers/carrierwave.rb

 

CarrierWave.configure do |config|

  config.storage = :grid_fs

  

  # Storage access url

  config.grid_fs_access_url = "/upload/grid"

end

 

 

3、在模型中设置要存储的文件

#>  app/models/user.rb

class User

  include Mongoid::Document

  mount_uploader :avatar, AvatarUploader

end

 

 

4、创建上传文件的管理器。

#> app/uploaders/avatar_uploader

class AvatarUploader < CarrierWave::Uploader::Base

  include CarrierWave::MiniMagick

 

  def store_dir

    "#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"

  end

 

  version :thumb do

    process :resize_to_limit => [200, 200]

  end

end

 

 

5、创建GridFS控制器。

#> app/controllers/gridfs_controller.rb

class GridfsController < ApplicationController

 

  def serve

    gridfs_path = env["PATH_INFO"].gsub("/upload/grid/", "")

    begin

      gridfs_file = Mongoid::GridFS[gridfs_path]

      self.response_body = gridfs_file.data

      self.content_type = gridfs_file.content_type

    rescue

      self.status = :file_not_found

      self.content_type = 'text/plain'

      self.response_body = ''

    end

  end

end

 

6、配置路由。

#> config/routes.rb

get "/upload/grid/*path" => "gridfs#serve"

 

你可能感兴趣的:(mongoid)