尝试在 Heroku (MongoHQ) 上使用 Sinatra 启动并运行 Mongoid。以前使用过 Rails,但第一次使用堆栈和 Sinatra。
从网络上的一个简单示例开始(app.rb
):
require 'rubygems'
require 'sinatra'
require 'mongo'
require 'mongoid'
configure do
Mongoid.load!('mongoid.yml')
Mongoid.configure do |config|
if ENV['MONGOHQ_URL']
conn = Mongo::Connection.from_uri(ENV['MONGOHQ_URL'])
uri = URI.parse(ENV['MONGOHQ_URL'])
# problem happens here
config.master = conn.db(uri.path.gsub(/^\//, ''))
else
config.master = Mongo::Connection.from_uri("mongodb://localhost:27017").db('test')
end
end
end
# Models
class Counter
include Mongoid::Document
field :count, :type => Integer
def self.increment
c = first || new({:count => 0})
c.inc(:count, 1)
c.save
c.count
end
end
# Controllers
get '/' do
"Hello visitor n" + Counter.increment.to_s
end
供参考,mongoid.yml
如下所示:
development:
sessions:
default:
database: localhost
production:
sessions:
default:
uri: <%= ENV['MONGOHQ_URL'] %>
根据app.rb (# problem happens here)
,我的日志说:
/app/app.rb:15:in `block (2 levels) in <top (required)>': undefined method `master=' for Mongoid::Config:Module (NoMethodError)
from /app/vendor/bundle/ruby/1.9.1/gems/mongoid-3.0.3/lib/mongoid.rb:112:in `configure'
from /app/app.rb:11:in `block in <top (required)>'
from /app/vendor/bundle/ruby/1.9.1/gems/sinatra-1.3.2/lib/sinatra/base.rb:1273:in `configure'
from /app/app.rb:8:in `<top (required)>'
我也尝试过变体,包括:
config.master = Mongo::Connection.from_uri(ENV['MONGOHQ_URL']).db('appXXXXX')
Mongoid.database = Mongo::Connection.from_uri(ENV['MONGOHQ_URL']).db('appXXXXXXX')
但得到同样的错误:
undefined method `master` for Mongoid::Config:Module (NoMethodError)
或者:
undefined method `database=` for Mongoid::Config:Module (NoMethodError)
我错过了什么?