I'm working on migrating our current Rails application(v 6.0.3.4) to a multi-tenant app where each client will have their own DB. The code works fine on my local environment but it gives ActiveRecord::ConnectionNotEstablished: No connection pool with 'primary' found for the 'reading' role error on staging.
I'm selecting the DB at the rack level depending on the subdomain.
module Middlewares
class Multitenancy
def initialize(app)
@app = app
end
def call(env)
@env = env
database = { writing: "primary_#{subdomain}".to_sym, reading: "replica_reader_#{subdomain}".to_sym }
ActiveRecord::Base.connected_to(database: database) do
@app.call(env)
end
end
private
def subdomain
ActionDispatch::Http::URL.extract_subdomain(@env['HTTP_HOST'], 1) unless @env['HTTP_HOST'].nil?
end
end
end
database.yml
default: &default
adapter: mysql2
encoding: utf8
# reconnect: false
host: <%= ENV.fetch("MYSQL_HOST") { '127.0.0.1' } %> # 127.0.0.1 to force use tcp ip instead of unix socket
database: <%= ENV.fetch("MYSQL_DB") { 'development' } %>
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } * 30 %>
username: <%= ENV.fetch("MYSQL_USER") { 'root' } %>
password: <%= ENV.fetch("MYSQL_PASSWORD") { '' } %>
port: <%= ENV.fetch("MYSQL_PORT") { '3306' } %>
variables:
sql_mode: TRADITIONAL
staging:
primary_subdomain_1:
<<: *default
host: <%= ENV.fetch("MYSQL_HOST") %>
replica_reader_subdomain_1:
<<: *default
host: <%= ENV.fetch("MYSQL_HOST_REPLICA") %>
replica: true
primary_subdomain_2:
<<: *default
host: %= ENV.fetch("MYSQL_HOST2") %>
replica_reader_subdomain_2:
<<: *default
host: %= ENV.fetch("MYSQL_HOST2_REPLICA") %>
replica: true
``