Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 316
evfwcqcg Avatar asked Apr 17 '12 12:04

evfwcqcg


2 Answers

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

like image 83
keyvan Avatar answered Oct 07 '22 07:10

keyvan


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

after do
  ActiveRecord::Base.connection.close
end
like image 21
bioneuralnet Avatar answered Oct 07 '22 08:10

bioneuralnet