# Many-to-many relationships between model using different db

**URL:** <https://www.ruby-forum.com/t/many-to-many-relationships-between-model-using-different-db/172178>\
**Category:** Rails\
**Created:** [July 16, 2009, 11:14am UTC](https://www.ruby-forum.com/t/many-to-many-relationships-between-model-using-different-db/172178 "2009-07-16T11:14:13Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![virendra](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/v/e68b1a/32.png) [@virendra](https://www.ruby-forum.com/u/virendra)\
**Post date:** [July 16, 2009, 11:14am UTC](https://www.ruby-forum.com/t/many-to-many-relationships-between-model-using-different-db/172178/1 "2009-07-16T11:14:13Z")

</div>

Hello to all  
I am finding out ways to set many-to-many relationships between my two  
models with each model belonging to a separate database.  
for e.g

1. I have a “User” Model belonging to “database\_1”
2. I have a “Project” Model which belongs to “database\_2”

Apparently there is many-to-many relationship between these two models.  
Had the Models been belonging to same databases my job would have been  
much easier I would either use hbtm or has\_many\_through associations for  
it  
but with each models belonging to there respective databases.I kind of  
got stuck with it  
Any Suggestion

Thank Anyway

---

<div class="post-metadata">

**Author:** ![virendra](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/v/e68b1a/32.png) [@virendra](https://www.ruby-forum.com/u/virendra)\
**Post date:** [July 16, 2009, 11:25am UTC](https://www.ruby-forum.com/t/many-to-many-relationships-between-model-using-different-db/172178/2 "2009-07-16T11:25:45Z")

</div>

Are you able to access both the databases in your single application?.  
If so, what connection settings you have?.

---

<div class="post-metadata">

**Author:** ![virendra](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/v/e68b1a/32.png) [@virendra](https://www.ruby-forum.com/u/virendra)\
**Post date:** [July 16, 2009, 11:59am UTC](https://www.ruby-forum.com/t/many-to-many-relationships-between-model-using-different-db/172178/3 "2009-07-16T11:59:20Z")

</div>

Rails L. wrote:

> Are you able to access both the databases in your single application?.  
> If so, what connection settings you have?.

Yes  
I have defined  
a second database in my database.yml like this  
development:  
adapter: mysql  
encoding: utf8  
reconnect: false  
database: database\_1  
pool: 5  
username: root  
password: root123  
host: localhost

database\_2:  
adapter: mysql  
reconnect: true  
database: database\_2  
username: root  
password: root123  
host: localhost

and i establish my connection for my second database like this  
class Project \< ActiveRecord::Base  
self.establish\_connection :database\_2  
end
