title: Understanding how establish_connection works in ActiveRecord
body: <p>This code was taken from ActiveRecord 2.3.14's gem class <code>ConnectionHandler</code></p>
  
  <pre><code>def establish_connection(name, spec)
    @connection_pools[name] = ConnectionAdapters::ConnectionPool.new(spec)
  end
  </code></pre>
  
  <p>It seems each time ruby calls <code>establish_connection</code> on the model, it's creating a new connection pool.</p>
  
  <p>My question: </p>
  
  <p>If I have 5 models that use <code>establish_connection</code> to the same database, is Rails smart enough to pick an already existing pool rather creating a new one with the same connection credentials? Does this also happen if my 5 models are subclasses of some abstract class that uses <code>establish_connection</code>? Will it always pick a connection from the <code>@connection_pools</code> if it exists?</p>
  
  <p><strong>Update 1</strong></p>
  
  <p>I'm talking about a concrete example. You have 5 models with 5 different connections, each time Rails uses a model it executes <code>establish_connection</code>. Looking at the code in ActiveRecord, when it executes <code>establish_connection</code> it creates a new pool with connections to that specific connection. What I'm wondering is whether each time Rails calls a model's <code>establish_connection</code>, does it create a new pool or take the existing one.</p>
  
  <p>Example: you come to my site and see a product list. You've just hit an action that calls <code>Product.all</code>, which executes <code>establish_connection</code> to some database on Amazon. Then, I come to the product list, what happens? Do I grab the established connection or am I creating a new pool with that connection?</p>
  
  <p><strong>Update 2</strong></p>
  
  <p>My guess is that first time Rails loads my models it's creating pools with different connections. After, when I use some <code>Model.method</code>, it just grabs the connection associated with the model and executes the method. </p>
  
  <p>I'm not sure what happens when 2 models have two equal connections (not in the abstract class but in self class). Will this produce two same connection pools, or is ActiveRecord smart enough to catch this case?</p>