# Dynamic Database Connections

**URL:** <https://www.ruby-forum.com/t/dynamic-database-connections/114460>\
**Category:** Rails\
**Created:** [September 12, 2007, 10:37pm UTC](https://www.ruby-forum.com/t/dynamic-database-connections/114460 "2007-09-12T22:37:23Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mike\_P](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/ba9def/32.png) [@Mike\_P](https://www.ruby-forum.com/u/Mike_P)\
**Post date:** [September 12, 2007, 10:37pm UTC](https://www.ruby-forum.com/t/dynamic-database-connections/114460/1 "2007-09-12T22:37:23Z")

</div>

We are creating a reporting/monitoring solution that will connect to  
multiple databases which are not rails compliant. That being said, the  
data being gathered is quite simple. BUT we won’t know what the  
connection details are until we access those details in another  
database record… confusing enough? Connection details are basically  
provided by a third party, so they have to be dynamic.

Am I doing this the wrong way? Why does it work on localhost, but not  
when opening a remote connection? (Something about the Name not being  
set…? )

Here is what I want to do:

The table reporting\_sites is on my localhost reporter\_production  
database. It has a field that contains the site name and database  
connection details for that database. For example, :db\_name =\>  
“FunActivities”, :conn\_details =\> { :host =\>  
‘[mydb.mysite.com](http://mydb.mysite.com)’, :username =\> ‘user1’, :password =\>  
‘mypwd’, :table\_name =\> ‘activities’, etc. etc… etc… }

My class looks like this…

class ReportingSite \< ActiveRecord::Base  
validates\_…

def after\_initialize  
self.conn = Class.new(ActiveRecord::Base)  
self.conn.establish\_connection(  
:adapter =\> “mysql”,  
:host =\> self.conn\_details[:host],  
:database =\> self.conn\_details[:database],  
:username =\> self.conn\_details[:user],  
:password =\> self.conn\_details[:password]  
)  
self.conn.set\_table\_name self.conn\_details[:table\_name]  
self.conn.set\_primary\_key self.conn\_details[:primary\_key]  
end  
end

It works every time when I am connecting to the local host and no  
other connection details (testing basically). But when I need to  
connect to another database, self.conn is created and I get this  
information in script/console

> > s1 = ReportingSite.find(1)  
> > =\> #\<ReportingSite:0x… ALL DETAILS HERE\>

> > s1.conn  
> > =\> #Class:0x...

> > s1.conn.methods  
> > =\> ALL ACTIVERECORD METHODS

> > s1.connection  
> > =\> #\<ActiveRecord::ConnectionAdapters::… ALL CONNECTION INFO FOR  
> > ReportingSite model\>

> > s1.conn.connection  
> > =\> NameError: “” is not a valid constant name!
