I have problem in build rails application that how to connect to multiple database in rails. After I searching i found how to fix my problem in here and in Rails Recipe B3 ebook.
By default Rails have a connection to one database per aplication. But if you want to connect to multiple databse, it’s very simple in rails. To create connection to multiple database in a rails application, we must set up named connection in database configuration(database.yml), configure model, and use inheritance to safely allow multiple models to use the new named connection.
In this case we have scenario like this :

connect to multiple database in rails
OK, let’s create a new rails application with mysql databse :
rails new multiple_database –database=mysql
In this case I use rails 3.1, but I think this same way in rails 3.0
Configure databse.yml to be like this:
development:
adapter: mysql2
encoding: utf8
reconnect: false
database: multiple_database_development
pool: 5
username: root
password: root
socket: /var/run/mysqld/mysqld.sock
external_development:
adapter: mysql2
encoding: utf8
reconnect: false
database: multiple_database_external
pool: 5
username: root
password: root
socket: /var/run/mysqld/mysqld.sock
Now create database whit this command line :
rake db:create:all
Create article and comment model :
rails g model article title:string content:text
rails g model comment article_id:integer name:string content:text
Open article model, and edit to be like this :
class Article < ActiveRecord::Base
has_many :comments
end
Open comment model, and edit to be like this :
class Comment < ActiveRecord::Base
establish_connection("external_development") #external_development is a named configuration in database.yml
belongs_to :article
end
Open create_comment migration file and add this section above def self.up in rails 3.0 or def change in rails 3.1:
def connection
Comment.connection
end
so it becomes like this :
class CreateComments < ActiveRecord::Migration
def connection
Comment.connection
end
def change
create_table :comments do |t|
t.integer :article_id
t.string :name
t.text :content
t.timestamps
end
end
end
Note : Comment.connection is a method to determine which database is used in migration as it has been declared in comment model.
Don’t forgate migrate file to database:
rake db:migrate
Open rails console, and chek connection :
create article
article = Article.create(:title => "First Article", :content => "Content of first article")
create comment
comment = article.comments.create(:name => "Dan", :content => "this is comment content")
Check database connection :
Article Connection
Article.connection.current_database
will be return :
=> "multiple_database_development"
Comment Connection
Comment.connection.current_database
will be return :
=> "multiple_database_external"
Now we can see that different database used. Article model use “multiple_database_development” database and comment model use “multiple_database_external” database.