Implementing multi database in Rails

119 views Asked by At

This is my first time implementing multi DB access in Rails and I am using version 6.1 for it.

My requirement is that all SELECT queries to model Product should go to my read replica. This is how I have setup multi DB access in Rails 6.1

class MultiDb < ApplicationRecord
  self.abstract_class = true

  connects_to database: { writing: :primary, reading: :primary_replica }
end

class Product < MultiDb
end

class User < ApplicationRecord
end

# database.yml
default: &default
  encoding: unicode
  pool: <%= ENV.fetch('DB_MAX_POOL') { 7 } %>

development:
  primary:
    <<: *default
    url: postgres://product_db_user:@localhost:5432/product_db
  primary_replica:
    <<: *default
    url: postgres://product_db_user:@localhost:5432/non_existing_product_db
    replica: true

The non_existing_product_db database does not exist and is meant to fail. But when I do Product.count from rails console, the query executes successfully, meaning the model is reading from primary and not primary_replica. Why is that? Shouldn't the query fail? ...since it should try and "read" from primary_replica.

Also, when I do the following...

ActiveRecord::Base.connected_to(role: :reading) do
  Product.count
end

I do see the following error - ActiveRecord::NoDatabaseError (FATAL: database "non_existing_product_db" does not exist)

0

There are 0 answers