ActiveRecord connection warning. (Database connections will not be closed automatically)

孤街浪徒 提交于 2019-12-18 04:04:24

问题


I'm trying to create a little app with Sinatra and ActiveRecord (3.2.3).

This is how my main file looks like:

require "sinatra"
require "sinatra/reloader"
require "active_record"
...

ActiveRecord::Base.establish_connection(
  adapter:  'sqlite3',
  database: 'db.sqlite3',
  host:     'localhost',
)

class Post < ActiveRecord::Base
  ...
end

get('/') { ... }
get('/posts') { ... }
...

It works, but sometimes I get a warning in console:

DEPRECATION WARNING: Database connections will not be closed automatically, please close your database connection at the end of the thread by calling close on your connection. For example: ActiveRecord::Base.connection.close'

When warning occurs it's takes a long time before page refreshes. I don't understand where I should close connection. I've tried to put ActiveRecord::Base.connection.close at the bottom of file, but it doesn't help.

update:

I forgot to mention that I also use sinatra/reloader plugin from sinatra-contrib gem to look at effect without restarting server.

require "sinatra/reloader"

If I comment it out then the problem disappears. But anyway, I'm wondering how to get rid of the problem without disabling reloader.


回答1:


You need to add a middleware to your stack. Just add this line to your config.ru rack up file:

use ActiveRecord::ConnectionAdapters::ConnectionManagement

Found the answer here: https://github.com/puma/puma/issues/59




回答2:


The accepted answer did not work for me in Sinatra on Thin (threaded mode). Instead I used:

after do
  ActiveRecord::Base.connection.close
end



回答3:


ActiveRecord::Base.remove_connection

Works fine for me and is listed in the docs.



来源:https://stackoverflow.com/questions/10191531/activerecord-connection-warning-database-connections-will-not-be-closed-automa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!