Skip to content

Multiple Schemas

Carlos edited this page Dec 25, 2022 · 1 revision

Add smooth support to managing and utilizing multiple schemas in your application. It works incredibly nicely with Inherited Tables and it's part of a larger feature for a better multi-tenancy application. PostgreSQL Docs

How it works

Configuration

This feature works with a whitelist/blacklist set of schemas, that filters, in a LIKE manner, the ones that will be present in the schema. These lists are extremely important so that not only can work properly, but also interact with other features from this gem.

default: &default
  adapter: postgresql
  encoding: unicode
  schemas:
    whitelist: ['internal']
    blacklist: ['external']

# OR a list of items, that also demonstrates the LIKE behavior
default: &default
  schemas:
    whitelist:
      - internal_%

This can also be configured exclusively for Torque, in your application.rb or similar place.

Torque::PostgreSQL.configure do |c|
  c.schemas.whitelist << 'internal'
  c.schemas.blacklist += %w[external other]
end

Migration

Once you stipulated which schemas will be supported in the configuration, you can now create a migration that creates it.

create_schema :internal

Models

There are 2 ways to set a model's schema. You can define it directly or use the model as the reference for all its models' schemas.

# Directly on the model
module Internal
  class User < ActiveRecord::Base
    self.schema = 'internal'
  end
end

# Indirect using the module
module Internal
  def self.schema
    'internal'
  end

  class User < ActiveRecord::Base
  end
end
Clone this wiki locally