# Dynamically switching database

**URL:** <https://www.ruby-forum.com/t/dynamically-switching-database/108762>\
**Category:** Rails\
**Created:** [July 6, 2007, 8:12pm UTC](https://www.ruby-forum.com/t/dynamically-switching-database/108762 "2007-07-06T20:12:25Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![tktktk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/a3d4f5/32.png) [@tktktk](https://www.ruby-forum.com/u/tktktk)\
**Post date:** [July 6, 2007, 8:12pm UTC](https://www.ruby-forum.com/t/dynamically-switching-database/108762/1 "2007-07-06T20:12:25Z")

</div>

Hi

I’m completely new to RoR and don’t know how to exactly achieve the  
following task:  
With our old web app we switched the database depending on the domain  
name so that we could use one application for multiple customers:

> [xy.com](http://xy.com) \> Database Xy  
> [yz.com](http://yz.com) \> Database Yz

This changed the database at the beginning of each visitor/users  
session. Is something like this achievable with RoR?

Thanks.

---

<div class="post-metadata">

**Author:** ![tktktk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/a3d4f5/32.png) [@tktktk](https://www.ruby-forum.com/u/tktktk)\
**Post date:** [July 6, 2007, 11:51pm UTC](https://www.ruby-forum.com/t/dynamically-switching-database/108762/2 "2007-07-06T23:51:45Z")

</div>

tk schrieb:

> This changed the database at the beginning of each visitor/users  
> session. Is something like this achievable with RoR?
> 
> Thanks.
> 
> >

there are a few options, but ultimately you’ll need to…

YourModel.establish\_connection(  
:adapter =\> mysql,  
:host =\> localhost,  
:username =\> xyz,  
:password =\> password,  
:database =\> params[‘dbinfo’]  
)

Where _params[‘dbinfo’]_ is the variable containing your database name.

this will set the connection to whichever database you need. You won’t  
(I don’t think) be able to do this within the model class. You’ll have  
to do it in a controller. Although you might want a default setting in  
the model class, for console work and such.

/ak
