# Connecting to multiple databases in rails in one application

**URL:** <https://www.ruby-forum.com/t/connecting-to-multiple-databases-in-rails-in-one-application/122631>\
**Category:** Rails\
**Created:** [December 10, 2007, 9:53am UTC](https://www.ruby-forum.com/t/connecting-to-multiple-databases-in-rails-in-one-application/122631 "2007-12-10T09:53:43Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![xgamerx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/x/d2c977/32.png) [@xgamerx](https://www.ruby-forum.com/u/xgamerx)\
**Post date:** [December 10, 2007, 9:53am UTC](https://www.ruby-forum.com/t/connecting-to-multiple-databases-in-rails-in-one-application/122631/1 "2007-12-10T09:53:43Z")

</div>

I need to be able to have a single rails application that has models  
from two different databases.Some models are in database 1 locally and  
some are in database 2 in a remote server. I need to be able to have  
models, migrations, fixtures and tests for all models and controllers  
connected to the two different databases. I am using Rails 2 and I  
really have a need for this to work.

Please point me in the direction of a plugin that will suit my needs.  
This seems like something that should be allowed in rails by now with a  
simple call:

def MyModel  
:database\_name =\> ‘second\_database’  
end

but nothing like this exists to my knowledge. Please help me. There has  
got to be a solution.

---

<div class="post-metadata">

**Author:** ![xgamerx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/x/d2c977/32.png) [@xgamerx](https://www.ruby-forum.com/u/xgamerx)\
**Post date:** [December 10, 2007, 4:37pm UTC](https://www.ruby-forum.com/t/connecting-to-multiple-databases-in-rails-in-one-application/122631/2 "2007-12-10T16:37:48Z")

</div>

The command you are looking for is establish\_connection. You might  
want to look at the rails rdoc. Search for “Connection to multiple  
databases in different models” in  
[Peak Obsession](http://api.rubyonrails.com/classes/ActiveRecord/Base.html).

eg:

class SomeModelDB1 \< ActiveRecord::Base  
self.establish\_connection(“db1”)  
end

class SomeModelDB2 \< ActiveRecord::Base  
self.establish\_connection(“db2”)  
end

database.yml  
db1:  
adapter: mysql  
database: somedb  
username: user  
password: pass  
host: localhost  
socket: /tmp/mysql.sock  
db2:  
adapter: mysql  
database: somedb2  
username: user  
password: pass  
host: remotehost

On Dec 10, 3:53 am, Nathan E. \<rails-mailing-l…@andreas-

---

<div class="post-metadata">

**Author:** ![xgamerx](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/x/d2c977/32.png) [@xgamerx](https://www.ruby-forum.com/u/xgamerx)\
**Post date:** [December 11, 2007, 3:12am UTC](https://www.ruby-forum.com/t/connecting-to-multiple-databases-in-rails-in-one-application/122631/3 "2007-12-11T03:12:16Z")

</div>

And this will allow me to have fixtures and tests for models that use a  
different database?
