Connecting Rails Project With Multiple Databases
I want to share my experience with multiple database and Rails 3.2 application. Today on one of my project i was in need to implement support ticketing system. Database for this system was already working for a good amount of time, so i was forced to use it as a source. So let’s start, first of all we should create base class in the /app/models/
, so we can inherit models, that will use external database as source.
1 2 3 4 5 6 7 8 |
|
The self.abstract_class = true
tells Active Record to not look up for a table, since this class is only used to add customm settings we don’t need any database table for it.
After that we should create a databases.rake file that will wrap database tasks for external database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
|
We basically get all the standart rake database tasks wrapped in the support namespace and redefine application paths, so rake will run this commands on the external database.
Now, let’s create files that we mention in this task:
db_support
folder in the root of applicationdb_support/migrate
folder for migrationsdb_support/seeds.rb
file with the seeds for support databaseconfig/database_support.yml
file with the settings for database connection
Here is an example of database_support.yml
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
The key is that you still want to use local database in the development and for the tests.
At this point we are pretty much done, now we can use commands like bundle exec rake support:db:create
to create development and test database. We also still able to use bundle exec rake db:migrate
for the default database.
This solution is pretty extensible, so it wouldn’t be hard to add as much databases as you need.