'Devise losing session when I'm using ActiveRecord::Base.establish_connection
Environment
- Ruby 2.6
- Rails 6.0
- Devise 4.7.2
- Database Postgres
Current behavior
Hi, I'm using a custom Middleware to connect to correct database based on subdmain
module Vtenancy
class WebTenancyMiddleware
def initialize(app)
@app = app
end
def call(env)
Rails.logger.info("env #{env['SERVER_NAME']}")
if (Vtenancy::Tenant.current = Vtenancy::Tenant.tenant_from_env(env))
Vtenancy::Tenant.current.establish_connection
@app.call(env)
else
[404, {}, []]
end
end
end
end
module Vtenancy
class Tenant < Vtenancy::ApplicationRecord
def self.current
if Rails.env.test?
@current
else
RequestStore.store[:tenant]
end
end
def self.current=(tenant)
if Rails.env.test?
@current = tenant
else
RequestStore.store[:tenant] = tenant
end
end
def establish_connection
Vtenancy::Tenant.current = self
ActiveRecord::Base.establish_connection(name.to_sym)
ActiveRecord::Base.connection.active?
ActiveRecord::Base.connection.enable_query_cache!
end
end
end
I add it before Warden::Manager
config.middleware.insert_before Warden::Manager, Vtenancy::WebTenancyMiddleware
But, when I access a page with a lot of requests, some fails with 401. Totally random
I'm using cookie session on Rails.
Edit 1
I changed the code a little bit because I read from rails issues (https://github.com/rails/rails/issues/37158) that connect to with database will be removed.
But anyway, using establish_connection have the same problem.
Edit 2
I set puma threads to one and now it's working. It's not the solution I need because It make my application note mult thread
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
