gpt4 book ai didi

ruby - Sinatra、Mongoid、Heroku、MongoHQ : connecting to Mongodb

转载 作者:可可西里 更新时间:2023-11-01 09:58:18 32 4
gpt4 key购买 nike

尝试在 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)

我错过了什么?

最佳答案

不应该

configure do
Mongoid.load!('mongoid.yml')
end

够了吗?

这就是 mongid docs 的内容正在说。 MONGOHQ_URL 环境变量已包含初始化数据库连接的所有信息。

关于ruby - Sinatra、Mongoid、Heroku、MongoHQ : connecting to Mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11804510/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com