<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Multiple Concurrent Database Connections with ActiveRecord</title>
      <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  
  <meta content="Multiple Concurrent Database Connections with ActiveRecord, Ruby, Rails, Database,  weare.buildingsky.net" name="description" />
  
  <meta name="generator" content="Typo 5.3">
  <meta content="Ruby, Rails, Database, " name="keywords" />
  <link rel="EditURI" type="application/rsd+xml" title="RSD" href="/xml/rsd" />
  <link rel="alternate" type="application/atom+xml" title="Atom" href="http://weare.buildingsky.net/2006/12/06/multiple-concurrent-database-connections-with-activerecord.atom" />
  <link rel="alternate" type="application/rss+xml" title="RSS" href="http://weare.buildingsky.net/2006/12/06/multiple-concurrent-database-connections-with-activerecord.rss" />
  <link href="/stylesheets/coderay.css?1251418886" media="all" rel="stylesheet" type="text/css" />
  <link href="/stylesheets/user-styles.css?1250794510" media="all" rel="stylesheet" type="text/css" />
  <script src="/javascripts/lang/en_US.js?1250794510" type="text/javascript"></script>

  <script src="/javascripts/cookies.js?1250794510" type="text/javascript"></script>

  <script type="text/javascript">
//<![CDATA[
window._token = '9dd1b280a0d3071bb5bc9f61089053bd28e01d48'
//]]>
</script>
  <script src="/javascripts/prototype.js?1250794510" type="text/javascript"></script>

  <script src="/javascripts/effects.js?1250794510" type="text/javascript"></script>

  <script src="/javascripts/typo.js?1250794510" type="text/javascript"></script>

  
  <script type="text/javascript"></script>
        <script type="text/javascript">
      var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
      document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
      </script>
      <script type="text/javascript">
      var pageTracker = _gat._getTracker("UA-831114-4");
      pageTracker._trackPageview();
      </script>

    
    <link href="/stylesheets/theme/sassified.css?1266420008" media="all" rel="stylesheet" type="text/css" />
    <script src="http://weare.buildingsky.net/processing-js/processing.js" type="text/javascript"></script>
  </head>
  <body>
    <div id="header">
      <div class="inside">
        <div id="search">
          <div class="searchimg"></div>
          <form action="/search" id="sform" method="get">
  <input type="text" id="q" name="q" value="" size="15" />
</form>

        </div>

        <a href="http://weare.buildingsky.net"><img src="/images/theme/header.png" /></a>
      </div>
    </div>

    <div id="page">
      <div id="content">
        <!--
<rdf:RDF
  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/"
  xmlns:dc="http://purl.org/dc/elements/1.1/">
<rdf:Description
  rdf:about=""
  trackback:ping="http://weare.buildingsky.net/trackbacks?article_id=1733"
  dc:title="Multiple Concurrent Database Connections with ActiveRecord"
  dc:identifier="http://weare.buildingsky.net/2006/12/06/multiple-concurrent-database-connections-with-activerecord"
  dc:description="ActiveRecord is a great tool to use for database maintenance as I explored in my previous article, Using ActiveRecord for Simple Maintenance Scripting, but what if you need to do tasks that require you to be connected to multiple databases at once. Perhaps"
  dc:creator="corban"
  dc:date="2009-08-20T16:14:45-04:00" />
</rdf:RDF>
-->

  <div id="primary" class="single-post">
    <div class="inside">
      <div class="primary">
        <div class="atomentry" id="article-1733">
  <h1 class="title"><a href="http://weare.buildingsky.net/2006/12/06/multiple-concurrent-database-connections-with-activerecord" rel="" class="">Multiple Concurrent Database Connections with ActiveRecord</a></h1>
  <div class="content">
    <p>ActiveRecord is a great tool to use for database maintenance as I explored in my previous article, <a href="http://schf.uc.org/articles/2005/08/09/using-activerecord-for-simple-maintenance-scripting">Using ActiveRecord for Simple Maintenance Scripting</a>, but what if you need to do tasks that require you to be connected to multiple databases at once.</p>


	<p>Perhaps you want to compare records in one database and copy them to another, well heres how you do it.</p>

          <div class="extended">
                  <h3>Configuration</h3>


	<p>Setup a database.yml file to contain your different database configurations.</p>


	<p><strong>database.yml</strong></p>


<div class="CodeRay"><pre><span class="CodeRay">database_1:
  adapter: mysql
  host: db1.host
  username: johnny 
  password: secret
  database: db1

database_2:
  adapter: mysql
  host: db2.host
  username: johnny 
  password: secret
  database: db2</span></pre></div>

	<h4>Setup database connections</h4>


	<p>Create a class for each database connection. The <strong>establish_connection</strong> method will load your <span class="caps">YAML</span> config for the desired database. Your models will inherit from these classes.</p>


<div class="CodeRay"><pre><span class="CodeRay">require <span class="s"><span class="dl">'</span><span class="k">active_record</span><span class="dl">'</span></span>

<span class="gv">$config</span> = <span class="co">YAML</span>.load_file(<span class="co">File</span>.join(<span class="co">File</span>.dirname(<span class="pc">__FILE__</span>), <span class="s"><span class="dl">'</span><span class="k">database.yml</span><span class="dl">'</span></span>))

<span class="r">class</span> <span class="cl">DatabaseA</span> &lt; <span class="co">ActiveRecord</span>::<span class="co">Base</span>
  establish_connection <span class="gv">$config</span>[<span class="s"><span class="dl">'</span><span class="k">database1</span><span class="dl">'</span></span>]
<span class="r">end</span>

<span class="r">class</span> <span class="cl">DatabaseB</span> &lt; <span class="co">ActiveRecord</span>::<span class="co">Base</span>
  establish_connection <span class="gv">$config</span>[<span class="s"><span class="dl">'</span><span class="k">database2</span><span class="dl">'</span></span>]
<span class="r">end</span></span></pre></div>

	<h4>Prepare Models</h4>


	<p>It is a good idea to separate each group of database models into its own module to avoid namespace clashes. In this example I have two databases which have the same schema (a production and development database perhaps). Each model must inherit from the Database class it belongs to, in this example either DatabaseA or DatabaseB.</p>


<div class="CodeRay"><pre><span class="CodeRay"><span class="r">module</span> <span class="cl">A</span>
  <span class="r">class</span> <span class="cl">Person</span> &lt; <span class="co">DatabaseA</span>
    has_one <span class="sy">:email</span>
  <span class="r">end</span>

  <span class="r">class</span> <span class="cl">Email</span> &lt; <span class="co">DatabaseA</span>
    belongs_to <span class="sy">:person</span>
  <span class="r">end</span>
<span class="r">end</span>

<span class="r">module</span> <span class="cl">B</span>
  <span class="r">class</span> <span class="cl">Person</span> &lt; <span class="co">DatabaseB</span>
    has_one <span class="sy">:email</span>
  <span class="r">end</span>

  <span class="r">class</span> <span class="cl">Email</span> &lt; <span class="co">DatabaseB</span>
    belongs_to <span class="sy">:person</span>
  <span class="r">end</span>
<span class="r">end</span></span></pre></div>

	<p>Separating the models into 2 different modules allows us to reference the same model name across multiple databases without colliding namespaces. eg. <strong>A::Person</strong> and <strong>B::Person</strong>.</p>


	<h3>Usage</h3>


	<p>For whatever reason I ended up having person records stored in my development database and I need them copied over to a production database.  
The problem is that each person record has associated table data, in this case  an emails table which must also be copied over with each record.</p>


	<h4>Copy a person from one database to another</h4>


	<p>First we will gank a person from the Database A (or development db) specifying the :include parameter in the finder args so that the email association is also stored in our receiving person object.</p>


	<p>Now that the person is copied we can make a new person specifying the Database B::Person model with the ganked person.attributes as our begining params.</p>


	<p>Next we can build associations, in this case the email association with the <strong>build_email</strong> method.</p>


	<p>When saving all primary and foreign keys will be reset to the new record&#8217;s id.</p>


<div class="CodeRay"><pre><span class="CodeRay">  person = <span class="co">A</span>::<span class="co">Person</span>.find_by_name(<span class="s"><span class="dl">'</span><span class="k">Corban Brook</span><span class="dl">'</span></span>, <span class="sy">:include</span> =&gt; [<span class="sy">:email</span>])

  new_person = <span class="co">B</span>::<span class="co">Person</span>.new person.attributes
  new_person.build_email person.email.attributes
  new_person.save</span></pre></div>

	<p>I would like to thank <strong>tshine</strong> from #radrails for his help.</p>
              </div>
      </div>
	<div class="meta">
    <div class="details">
		
		
    </div>
		<br style="clear:both;" />
	</div>
</div>


        <script type="text/javascript"><!--
          google_ad_client = "pub-3895450589978750";
          google_ad_width = 728;
          google_ad_height = 90;
          google_ad_format = "728x90_as";
          google_ad_type = "text";
          google_ad_channel ="7564446153";
          google_color_border = "FFFFFF";
          google_color_bg = "FFFFFF";
          //google_color_border = "C2E5FF";
          //google_color_bg = "C2E5FF";
          google_color_link = "0A68BB";
          google_color_text = "304050";
          google_color_url = "505050";
        //--></script>
        <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

      </div>
      <hr class="hide" />
      <div class="secondary">
        <h2>About this entry</h2>
        <div class="featured">
          <dl>
            <dt>Author:</dt>
            <dd>Corban Brook</dd>
          </dl>
          <dl>
            <dt>Published:</dt>
            <dd><abbr class="published" title="2006-12-06T15:52:00-05:00"><span class="typo_date date gmttimestamp-1165438320" title="Wed, 06 Dec 2006 20:52:00 GMT" >Wed, 06 Dec 2006 20:52:00 GMT</span></abbr></dd>
          </dl>
          
          <dl>
            <dt>Category:</dt>
            <dd><a href="http://schf.uc.org/category/ruby" rel="tag">Ruby</a>, <a href="http://schf.uc.org/category/rails" rel="tag">Rails</a>, <a href="http://schf.uc.org/category/database" rel="tag">Database</a></dd>
          </dl>
          
          
          
          <div style="margin-top:20%;">
          <h2>Follow us on twitter</h2>
          <ul class="dates">
            <li><a href="http://twitter.com/corban">Corban Brook</a></li>
            <li><a href="http://twitter.com/maciek416">Maciek Adwent</a></li>
          </ul>
          </div>


        </div>

      </div>
      <div class="clear"></div>
    </div>
  </div>
 
  <hr class="hide" />

  <div id="secondary" class="single-post">
    <div class="inside">
      <div class="primary">
        
                  
            <h1 class="title"><a name="comments">Comments</a></h1>
          
          <div id="comments_div">
            <ol id="commentList" class="comments">
      <li class="comment" id="comment-63">
  <div class="author">
    <div><img alt="Avatar" class="gravatar" src="http://www.gravatar.com/avatar.php?gravatar_id=d41d8cd98f00b204e9800998ecf8427e&amp;size=60" /></div>
    <h2>Mr eel</h2>
    <div></div>
    <div>Posted: <abbr title="2006-12-06T20:30:52-05:00">about 5 hours later:</abbr></div>
  </div>
  <div class="clear"></div>
    <p>Very nice!</p>


	<p>Now I&#8217;ve been trying to think of a nice way to share models and data between applications — in particular users — and this looks like it might be the way to do it.</p>
  </li>

<li class="comment" id="comment-69">
  <div class="author">
    <div><img alt="Avatar" class="gravatar" src="http://www.gravatar.com/avatar.php?gravatar_id=30ee518e6fdc5b07e060775b5a542bdb&amp;size=60" /></div>
    <h2>Jon Gretar</h2>
    <div><a href="http://www.jongretar.net">http://www.jongretar.net</a></div>
    <div>Posted: <abbr title="2006-12-08T12:06:17-05:00">1 day later:</abbr></div>
  </div>
  <div class="clear"></div>
    <p>Funny&#8230; I just wrote a similar tutorial for Camping couple of days ago.</p>
  </li>

<li class="comment" id="comment-70">
  <div class="author">
    <div><img alt="Avatar" class="gravatar" src="http://www.gravatar.com/avatar.php?gravatar_id=d41d8cd98f00b204e9800998ecf8427e&amp;size=60" /></div>
    <h2>JonGretar</h2>
    <div></div>
    <div>Posted: <abbr title="2006-12-08T19:36:02-05:00">2 days later:</abbr></div>
  </div>
  <div class="clear"></div>
    <p>Except this one is more useful and better an all ways&#8230;.. ;)</p>
  </li>

<li class="comment" id="comment-66">
  <div class="author">
    <div><img alt="Avatar" class="gravatar" src="http://www.gravatar.com/avatar.php?gravatar_id=c381828d1907912eab30cbe38d5ea245&amp;size=60" /></div>
    <h2>Aníbal Rojas</h2>
    <div><a href="http://www.rubycorner.com">http://www.rubycorner.com</a></div>
    <div>Posted: <abbr title="2006-12-10T21:28:34-05:00">4 days later:</abbr></div>
  </div>
  <div class="clear"></div>
    <p>Off Topic: This is just a quick note to invite you to register your blog at RubyCorner.com, a directory for blogs related to the Ruby Programming Language or any of the related technologies and projects.</p>
  </li>

<li class="comment" id="comment-67">
  <div class="author">
    <div><img alt="Avatar" class="gravatar" src="http://www.gravatar.com/avatar.php?gravatar_id=d41d8cd98f00b204e9800998ecf8427e&amp;size=60" /></div>
    <h2>eee</h2>
    <div></div>
    <div>Posted: <abbr title="2006-12-10T23:53:48-05:00">4 days later:</abbr></div>
  </div>
  <div class="clear"></div>
    <p>ee</p>
  </li>

<li class="comment" id="comment-68">
  <div class="author">
    <div><img alt="Avatar" class="gravatar" src="http://www.gravatar.com/avatar.php?gravatar_id=d41d8cd98f00b204e9800998ecf8427e&amp;size=60" /></div>
    <h2>jan.</h2>
    <div></div>
    <div>Posted: <abbr title="2006-12-15T05:29:31-05:00">8 days later:</abbr></div>
  </div>
  <div class="clear"></div>
    <p>Thanks for that! I&#8217;ve been looking for this functionality for a long time.</p>


	<p>Unfortunately, I can&#8217;t get it to work&#8230; Using the exact snippet as above pointing to a working database, I get the error:</p>


	<pre><code>relation "database_as" does not exist</code></pre>


	<p>The DatabaseA class is considered a <em>table</em> instead of a database connection.</p>
  </li>

<li class="comment" id="comment-4">
  <div class="author">
    <div><img alt="Avatar" class="gravatar" src="http://www.gravatar.com/avatar.php?gravatar_id=d41d8cd98f00b204e9800998ecf8427e&amp;size=60" /></div>
    <h2>jan.</h2>
    <div></div>
    <div>Posted: <abbr title="2006-12-15T05:54:23-05:00">8 days later:</abbr></div>
  </div>
  <div class="clear"></div>
    <p>Found the solution to the &#8220;database_as does not exist&#8221; problem (from the Rails Recipes book): had to add &#8220;self.abstract_class = true&#8221; to the DatabaseA class.</p>
  </li>

<li class="comment" id="comment-62">
  <div class="author">
    <div><img alt="Avatar" class="gravatar" src="http://www.gravatar.com/avatar.php?gravatar_id=d41d8cd98f00b204e9800998ecf8427e&amp;size=60" /></div>
    <h2>jimmy</h2>
    <div></div>
    <div>Posted: <abbr title="2006-12-18T20:29:12-05:00">12 days later:</abbr></div>
  </div>
  <div class="clear"></div>
    <p>Having troubles&#8230; so, is this:</p>


	<p>establish_connection $config[&#8216;database1&#8217;]</p>


	<p>actually, supposed to be:</p>


	<p>establish_connection $config[&#8216;database_1&#8217;]</p>


	<p>note the underscore in the second one.</p>
  </li>


  </ol>

          </div>
              </div>
      <div class="secondary">
        
      </div>
      <div class="clear"></div>
    </div>
  </div>



        <script type="text/javascript">
//<![CDATA[
show_dates_as_local_time()
//]]>
</script>
      </div>
    </div>

    <div id="ancillary">
      <div class="inside">
        <div class="block first">
          <h1>About</h1>
<ul class="dates">
<p>
  Buildingsky.net is comprised of <a href="http://twitter.com/corban">Corban Brook</a> and 
  <a href="http://twitter.com/maciek416">Maciek Adwent</a>. We build experimental web applications.
</p>
<p>
  We are interested in computer science, ruby-lang, javascript, web technologies, audio synthesis, finance/economics. 
</p>
</ul>
<h2>Contact</h2>
<ul class="dates">
  <li><a href="http://twitter.com/corban">Corban Brook</a> <span class="date">Follow on twitter</span></li>
  <li><a href="http://twitter.com/maciek416">Maciek Adwent</a> <span class="date">Follow on twitter</span></li>
</ul>
<h2>Projects</h2>
<ul class="dates">
  <li><span class="date">Twitter Authentication</span> <a href="http://www.github.net/corbanbrook/twitter_authentication">Github</a></li>
  <li><span class="date">Spectrotune</span> <a href="http://www.github.com/corbanbrook/spectrotune">Github</a> | <a href="http://www.vimeo.com/1932816">Vimeo</a></li>
  <li><span class="date">RComposit</span> <a href="http://www.github.net/corbanbrook/rcomposite">Github</a></li>
  <li><a href="http://www.scrapmetl.com">Scrapmetl.com</a></li>
</ul>

        </div>

        <div class="block">
          <h1>Recently</h1>
<ul class="dates">
  
    <li><span class="date">Jun 17</span> <a href="http://weare.buildingsky.net/2010/06/17/html5-audio-data-api" rel="" class="">HTML5 Audio Data API (Videos)</a></li>
  
    <li><span class="date">Feb 19</span> <a href="http://weare.buildingsky.net/2010/02/19/git-for-humans" rel="" class="">Git for humans</a></li>
  
    <li><span class="date">Jan 07</span> <a href="http://weare.buildingsky.net/2010/01/07/html5-audio-tag-with-realtime-javascript-fft-visualization" rel="" class="">HTML5 audio tag with realtime javascript FFT visualization</a></li>
  
    <li><span class="date">Nov 23</span> <a href="http://weare.buildingsky.net/2009/11/23/understanding-spectral-leakage-and-window-functions" rel="" class="">Understanding spectral leakage and window functions </a></li>
  
    <li><span class="date">Nov 15</span> <a href="http://weare.buildingsky.net/2009/11/15/metaworker-javascript-library-released-alpha" rel="" class="">Metaworker javascript library released (alpha)</a></li>
  
    <li><span class="date">Oct 08</span> <a href="http://weare.buildingsky.net/2009/10/08/mechanical-reproduction-of-digitized-speech-on-a-piano" rel="" class="">Mechanical reproduction of digitized speech on a piano</a></li>
  
    <li><span class="date">Sep 08</span> <a href="http://weare.buildingsky.net/2009/09/08/spectrotune-v0-5-1-released" rel="" class="">Spectrotune v0.5.1 Released</a></li>
  
    <li><span class="date">Sep 01</span> <a href="http://weare.buildingsky.net/2009/09/01/spectrotune-added-to-github" rel="" class="">Spectrotune added to github</a></li>
  
    <li><span class="date">Aug 25</span> <a href="http://weare.buildingsky.net/2009/08/25/rubys-metaprogramming-toolbox" rel="" class="">Ruby's Metaprogramming Toolbox</a></li>
  
    <li><span class="date">Aug 14</span> <a href="http://weare.buildingsky.net/2009/08/14/twitter-authentication-rails-plugin-added-to-github" rel="" class="">Twitter Authentication Rails Plugin added to Github</a></li>
  
</ul>

        </div>

        <div class="block">
          <h1>Categories</h1>
          <ul class="dates">
  
  <li><a href="http://schf.uc.org/category/javascript">Javascript</a> <span class="date">(10)</span></li>
  
  
  <li><a href="http://schf.uc.org/category/ruby">Ruby</a> <span class="date">(12)</span></li>
  
  
  <li><a href="http://schf.uc.org/category/xml">XML</a> <span class="date">(1)</span></li>
  
  
  <li><a href="http://schf.uc.org/category/dom">DOM</a> <span class="date">(2)</span></li>
  
  
  <li><a href="http://schf.uc.org/category/php">PHP</a> <span class="date">(1)</span></li>
  
  
  
  <li><a href="http://schf.uc.org/category/os-x">OS X</a> <span class="date">(4)</span></li>
  
  
  <li><a href="http://schf.uc.org/category/macbookpro">MacBook Pro</a> <span class="date">(2)</span></li>
  
  
  <li><a href="http://schf.uc.org/category/rails">Rails</a> <span class="date">(9)</span></li>
  
  
  <li><a href="http://schf.uc.org/category/database">Database</a> <span class="date">(3)</span></li>
  
  
  <li><a href="http://schf.uc.org/category/cellular-phones">Cellular Phones</a> <span class="date">(1)</span></li>
  
  
  
  <li><a href="http://schf.uc.org/category/processing">Processing</a> <span class="date">(6)</span></li>
  
  
  <li><a href="http://schf.uc.org/category/finance">Finance</a> <span class="date">(2)</span></li>
  
  
  <li><a href="http://schf.uc.org/category/audio">Audio</a> <span class="date">(3)</span></li>
  
  
  <li><a href="http://schf.uc.org/category/html5">HTML5</a> <span class="date">(1)</span></li>
  
  
  <li><a href="http://schf.uc.org/category/git">Git</a> <span class="date">(1)</span></li>
  
</ul>


        </div>
        <div class="clear"></div>
      </div>
    </div>
    <div id="footer">
      <div class="inside">
        <p class="copyright"><a href="http://weare.buildingsky.net">Buildingsky.net</a></p>
        <p class="attributes"><b>Syndicate</b><a href="/articles.rss" title="Articles feed">Articles RSS</a><a href="/comments.rss" title="Comments feed">Comments RSS</a></p>
        </ul>
        <div class="clear"></div>
      </div>
    </div>
  </body>
</html>



