To prevent connection leak in multi threads, you have to manage the connection manually. You can try:
Thread.new do
ActiveRecord::Base.connection_pool.with_connection do
# Do whatever
end
end
One problem of ActiveRecord::Base.connection_pool.with_connection
is that it always prepare a connection even if the code inside does not need it.
We can improve it a little bit by using ActiveRecord::Base.connection_pool.release_connection
:
Thread.new do
begin
# Do whatever
ensure
ActiveRecord::Base.connection_pool.release_connection
end
end