Using multiple PostgreSQL schemas with Rails models Using multiple PostgreSQL schemas with Rails models ruby-on-rails ruby-on-rails

Using multiple PostgreSQL schemas with Rails models


PostgreSQL adapter schema_search_path in database.yml does solve your problem?

development:  adapter: postgresql  encoding: utf-8  database: solidus  host: 127.0.0.1  port: 5432  username: postgres  password: postgres  schema_search_path: "discogs,public"

Or, you can to specify different connections for each schema:

public_schema:  adapter: postgresql  encoding: utf-8  database: solidus  host: 127.0.0.1  port: 5432  username: postgres  password: postgres  schema_search_path: "public"discogs_schema:  adapter: postgresql  encoding: utf-8  database: solidus  host: 127.0.0.1  port: 5432  username: postgres  password: postgres  schema_search_path: "discogs"

After each connection defined, create two models:

class PublicSchema < ActiveRecord::Base  self.abstract_class = true  establish_connection :public_schemaendclass DiscoGsSchema < ActiveRecord::Base  self.abstract_class = true  establish_connection :discogs_schemaend

And, all your models inherit from the respective schema:

class MyModelFromPublic < PublicSchema  set_table_name :my_table_nameendclass MyOtherModelFromDiscoGs < DiscoGsSchema  set_table_name :discoend

I hope it helps.


In migrations:

class CreateUsers < ActiveRecord::Migration  def up    execute 'CREATE SCHEMA settings'    create_table 'settings.users' do |t|      t.string :username      t.string :email      t.string :password      t.timestamps null: false    end  end  def down    drop_table 'settings.users'    execute 'DROP SCHEMA settings'  endend

Optional in model

class User < ActiveRecord::Base  self.table_name 'settings.users'end