本文介绍了ActiveRecord 连接警告.(数据库连接不会自动关闭)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Sinatra 和 ActiveRecord (3.2.3) 创建一个小应用程序.

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:

弃用警告:数据库连接不会关闭自动,请在结束时关闭您的数据库连接通过在您的连接上调用 close 来处理线程.例如:ActiveRecord::Base.connection.close'

出现警告时,页面刷新需要很长时间.我不明白我应该在哪里关闭连接.我尝试将 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.

更新:

我忘了提到我还使用 sinatra-contrib gem 中的 sinatra/reloader 插件不用重启服务器看效果.

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.

推荐答案

您需要向堆栈中添加一个中间件.只需将此行添加到您的 config.ru 机架文件中:

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

use ActiveRecord::ConnectionAdapters::ConnectionManagement

在这里找到答案:https://github.com/puma/puma/issues/59

这篇关于ActiveRecord 连接警告.(数据库连接不会自动关闭)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 19:02