Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple PostgreSQL schemas with Rails models

I have a PostgreSQL database for my Rails application. In the schema named 'public' the main Rails models tables are stored etc. I have created a 'discogs' schema which will have tables with names that are sometimes the same as in the 'public' schema - which is one of the reasons that I'm using schemas to organize this.

How would I setup models from the 'discogs' schema in my app? I will be using Sunspot to let Solr index these models as well. I'm unsure of how you would do this.

like image 248
Johan Avatar asked Jan 10 '12 15:01

Johan


People also ask

How many schemas can you have in Postgres?

A database can contain one or multiple schemas and each schema belongs to only one database. Two schemas can have different objects that share the same name.

Can Postgres have multiple databases?

A single Postgres server process can manage multiple databases at the same time. Each database is stored as a separate set of files in its own directory within the server's data directory. To view all of the defined databases on the server you can use the \list meta-command or its shortcut \l .


1 Answers

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_schema end  class DiscoGsSchema < ActiveRecord::Base   self.abstract_class = true   establish_connection :discogs_schema end 

And, all your models inherit from the respective schema:

class MyModelFromPublic < PublicSchema   set_table_name :my_table_name end  class MyOtherModelFromDiscoGs < DiscoGsSchema   set_table_name :disco end 

I hope it helps.

like image 167
Felsangom Avatar answered Sep 22 '22 11:09

Felsangom