Ruby on Rails
HowtoUseMultipleDatabasesOnePerTable

The HowtoUseMultipleDatabases refers to the ActiveRecord::Base documentation for connecting to multiple databases in different models but I found that documentation confusingly vague.

It is clear that you can call ExampleModel.establish_connection to change the connection that model uses, but doing this in environment.rb will only effect the first query. After that the model reverts to the default. As it turns out, it’s explained in the blog by some guy named gabriel at
http://www.chwhat.com/articles/2005/10/01/multiple-databases-on-rails

What you have to do is call establish_connection with the alternate database’s parameters inside the class of the model you want to change.

Here’s his example:


class MyTags < ActiveRecord::Base
establish_connection({
:adapter => “mysql”,
:username => “bozo”,
:password => “bogus”,
:database => “tags”
})
set_table_name “tags”
end

This way, no matter where or when an instance of class MyTags is created, it will be attached to the alternate database.

—jacob

You can define the database in config/database.yml as mentioned in HowtoUseMultipleDatabases:

tags_development:
  adapter: mysql
  database: tags
  username: bozo
  password: bogus

tags_test:
...

tags_production:
...

but put the establish_connection line in the model:

class MyTags < ActiveRecordLLBase
  establish_connection "tags_#{RAILS_ENV}"
  set_table_name "tags"
end

WARNING this is a BAD thing to do. This will cause a new connection to be opened each time the model is used, and it doesn’t get closed, or reused. If someone has a good way to reuse the connection, please post it. — Ken

NOTE: You may have to lose the curly braces for establish_connection and just use the normal round brackets. That’s the only way it worked for me — Ennis.