configure a rails app for multiple databases

Hello Rails community

I cannot seem to find via Google what I had hoped would be a simple issue

On a single DB system (currently, postgres 8.1.4), I have two databases, each containing multiple tables.

I would like to configure my app and database.yml to recognize these two databases.

What is the corrrect config for the database.yml ? Is it something like:

production:   adapter: postgresql   database: database1, database2 etc.


Is there some trick involved with this kind of configuration ?

Presumably, I would have open two db connections within the app, as a result of which, dereferencing the db off of these would uniquely identify the respective database and its tables. But of course, I hope it would be ActiveRecord keeping track of these distinctions. But then, maybe this is not so, and it is necessary to fully qualify the accesses to elements of the tables.

Anyhow, could someone please point me to info and examples of this nature of access ?

Of course, doing this kind of thing in ruby itself is simple - I've done this for simultaneous access to MySql and postgres, as in when I transfered tables from the one to the other.

Maurice Yarrow

You don't have to get all complicated and establish another connection if it's on the same server. The way I've been doing it - I just have...3 models that are in a separate database.

set_table_name 'otherdb.tablename'

That's all I have to do. It's not really DRY, but you're going to have to specify which database to connect to in each model that doesn't use the default DB anyway. Anyone has a better way, I'd like to hear it.

Maurice Yarrow wrote:

Each of your models use the database connection defined in database.yml unless otherwise specified. If you're using two databases, make one your primary and stick its information in database.yml. For all your models which use THE OTHER database(s) you need to tell each of them to use a different connection.

Check out: Peak Obsession in the section where it says "Connection to multiple databases in different models"

You'll need to plug the following into each model.rb file that uses the secondary database(s):

ActiveRecord::Base.establish_connection( :adapter => "mysql", :host => "localhost", :username => "myuser", :password => "mypass", :database => "somedatabase" )

You can make it a bit simpler... in database.yml put:

other_db:    adapter: mysql    database: somedatabase    username: myuser    password: mypass    host: localhost

And then in your model put:

   establish_connection "other_db"

In fact if you have a group of models that will use that table *and* they are logically connected (say all parts of a blog system or whatever) you could do:

class BlogSystem < ActiveRecord::Base    establish_connection "other_db" end

class Blog < BlogSystem end

class BlogPost < BlogSystem end


Very nice. Very clean. Very DRY.

Philip Hallstrom wrote: