我遇到了麻烦,试图将 CarrierWave 用于在 Rails 3 中开发的文件上传 Rest API 和 MongoDB 数据库。
我想做的是使用 MongoDB 系统 GridFS 存储一些文件(不仅是图像,而且是每种文件格式)。我阅读了许多建议我使用 CarrierWave gem 的文档。
但是当我尝试配置它时出现错误。
我的开发环境:Gemfile:
source 'https://rubygems.org'
gem 'rails', '3.2.8'
# MongoDB
gem 'mongoid', :git => 'git://github.com/mongoid/mongoid.git'
gem 'carrierwave', :git => "git://github.com/jnicklas/carrierwave.git"
# gem 'carrierwave-mongoid', :require => 'carrierwave/mongoid'
gem 'mini_magick', :git => 'git://github.com/probablycorey/mini_magick.git'
gem 'bson_ext'
gem 'json'
应用程序.rb :
require File.expand_path('../boot', __FILE__)
# ActiveRecord will not be use with MongoDB
# require 'rails/all'
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "rails/test_unit/railtie"
require "sprockets/railtie"
require "mongoid/railtie"
require "carrierwave"
# require "carrierwave/mongoid"
我使用 mongoid.yml (config/mongoid.yml) 文件定义数据库:
development:
sessions:
default:
database: lf_rest_api_development
hosts:
- localhost:27017
options:
consistency: :strong
options:
test:
sessions:
default:
database: lf_rest_api_test
hosts:
- localhost:27017
options:
consistency: :strong
并使用初始化程序 (config/initializers/mongoid.rb) 加载它:
Mongoid.load!("config/mongoid.yml")
-- 在最后一个文件 config/initializers/carrierwave.rb 之后,我可以毫无问题地执行“rails server”命令:
CarrierWave.configure do |config|
config.grid_fs_database = Mongoid.database.name
config.grid_fs_host = Mongoid.config.master.connection.host
config.storage = :grid_fs
config.grid_fs_access_url = "/files"
end
然后当我运行“rails server”命令时出现以下错误:
=> Booting WEBrick
=> Rails 3.2.8 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
Exiting
/{API_path}/config/initializers/zcarrierwave.rb:4:in `block in <top (required)>': undefined method `database' for Mongoid:Module (NoMethodError)
[...]
我的文件模型定义如下:
require 'carrierwave/orm/mongoid'
class File
include Mongoid::Document
store_in_collection: "files", database: "lf_rest_api_developement", session: "default"
key :filename, type: String
key :content_type, type: String
key :length, type: BigDecimal
key :chunk_size, type: Integer, :default => 256
key :upload_date, type: DateTime
key :md5, type: String
key :metadata, type: Array, :default => []
mount_uploader :file, FileUploader
index({ location: "2d" }, { min: -200, max: 200 })
end
FileUploader 只是 CarrierWave 上传器的扩展......
class FileUploader < CarrierWave::Uploader::Base
storage :grid_fs
end