这是我的第一个 Sinatra 项目,我已经很晚了,我意识到当一次使用 ActiveRecord 发出多个请求时,我遇到了问题。如果我只提出一个要求,那么每个要求都是独立的。但是当我同时调用两者时,我会失败。
到目前为止,我已将其范围缩小到同时存在两个 ActiveRecord 请求的问题。也许我没有正确设置 ActiveRecord?我使用 PostgreSQL 是因为 Heroku 使用它,并且不打算改变。(这个问题也发生在 Heroku 上。)
这是日志:
192.168.1.113 - - [30/Sep/2012:10:33:00 MDT] "GET /version/current?platform=android HTTP/1.1" 200 33
- -> /version/current?platform=android ActiveRecord::StatementInvalid - NoMethodError: undefined method `fields' for nil:NilClass: SELECT "rankings".* FROM "rankings" WHERE "rankings"."user_id" = 1 LIMIT 1:
/Users/zablanc/.rvm/gems/ruby-1.9.3-head@emm/gems/activerecord-3.2.7/lib/active_record/connection_adapters/postgresql_adapter.rb:667:in `block in exec_query'
...
Warning! Rack::Session::Cookie data size exceeds 4K.
Warning! Rack::Session::Cookie failed to save session. Content dropped.
192.168.1.113 - - [30/Sep/2012:10:33:01 MDT] "GET /badges/all HTTP/1.1" 200 311
- -> /badges/all
192.168.1.113 - - [30/Sep/2012:10:33:01 MDT] "GET /moves/ranking/all HTTP/1.1" 500 166185
- -> /moves/ranking/all
我不知道如何关闭这些 cookie 警告,但它们似乎对应用程序没有影响。这是我配置我的应用程序的方式(在我需要主脚本的配置文件中):
enable :logging
use ActiveRecord::ConnectionAdapters::ConnectionManagement
use Rack::Session::Cookie, :key => 'rack.session',
:path => '/',
:expire_after => 31_536_000, # In seconds
:secret => 'jeowkfj...secret...kjn5'
ActiveRecord::Base.include_root_in_json = false
def establish_connection(url)
db = URI.parse(url)
ActiveRecord::Base.establish_connection(
:adapter => db.scheme == 'postgres' ? 'postgresql' : db.scheme,
:host => db.host,
:port => db.port,
:username => db.user,
:password => db.password,
:database => db.path[1..-1],
:encoding => 'utf8'
)
end
configure :development do
establish_connection('postgres://postgres:postgres@localhost:5432/emm')
end
configure :test do
establish_connection('postgres://postgres:postgres@localhost:5432/emm-test')
end
configure :production do
establish_connection(ENV['DATABASE_URL'])
end
我猜我没有正确设置 ActiveRecord,但我认为它就像我看过的教程一样。是什么赋予了?