Ruby on Rails connect to Multiple Databases and using ActiveRecord with multiple databases, it’s really simple take it easy. Let’s run through this.
Well, I want to handle migrations for two databases, so I need two separate Rake tasks to handle that:
My first task is
db:migrate that delegates out to
Each of those establish a connection to the database and then runs the migrations from their own separate folders. This allows you to store migrations in separate folders so you can easily manage them.
The migrations are exactly the same as normal.
In order to get those migrations to work, I need to configure the database connections. I’m going to define everything in the
database.yml just like normal, but with a different naming convention:
I configure two separate databases db1 & db2.
Then I need to configure the app to load these now. I open
application.rb or environment file(s):
Take a look at what’s going on:
– I set the database configuration to use. You can just use Rails.env here instead of ENV[‘ENV’].
– I load up the database.yml config and parse it with YAML.
– I grab the configuration from the file for each db and the correct environment that I’m running in.
When I’m working with multiple databases, I like to explicitly setup the connections inside the models themselves instead of inheriting from ActiveRecord::Base and using subclasses.
Well, All you really need to do is load the configurations, establish the database connections, and setup the migrations to load from a specific directory for each database.
Don’t know how to build task…
Try renaming the file to sample_data.rake.
I was able to get your example working (replacing the internals of the task with a p statement) by putting your code in a file called testomatic.rake in lib/tasks.