title: How to establish_connection with more than one database in parallel in Rails?
body: <h2>Context</h2>
  
  <p>I'm building a SaaS where users can create their own websites (like Wix or SquareSpace).
  That's what happens behind scenes:</p>
  
  <ul>
  <li>My app has its main database which stores users</li>
  <li>When a user creates his website, an external database is created to store its data</li>
  <li>SQL file runs in this external database to set default settings</li>
  <li>Other users shall create their websites simultaneously</li>
  </ul>
  
  <hr>
  
  <h2>Approach</h2>
  
  <p>To <em>create a new database</em> and <em>establish connection</em> I do the following:</p>
  
  <pre><code>ActiveRecord::Base.connection.execute("CREATE DATABASE #{name}")
  ActiveRecord::Base.establish_connection(&lt;dynamic db data&gt;)
  </code></pre>
  
  <p>Then I <em>execute sql</em> code in the db by doing:</p>
  
  <pre><code>sql = File.read(sql_file.sql)
  statements = sql.split(/;$/)
  statements.pop
  ActiveRecord::Base.transaction do
    statements.each do |statement|
      connection.execute(statement)
    end
  end
  </code></pre>
  
  <p>Then I reestablish connection with main db:</p>
  
  <pre><code>ActiveRecord::Base.establish_connection :production
  </code></pre>
  
  <hr>
  
  <h2>Problem</h2>
  
  <ol>
  <li>Establishing connection to dynamic database makes application's main database inacessible for a while:
  
  <ul>
  <li>User A is creating a website (establishes dynamic database connection)</li>
  <li>User B tries to access his user area (which requires application's main db data)</li>
  <li>Application throws an error because it tries to retrieve data of app-main-db (which connection is not established at the moment)</li>
  </ul></li>
  </ol>
  
  <p>How can I handle many users creating their websites simultaneously without databases conflict?</p>
  
  <p>In other words, how can I <code>establish_connection</code> with more than one database in parallel?</p>
  
  <hr>
  
  <p><em>NOTE:
  It is not the same as connecting to multiple databases through database.yml. The goal here is to connect and disconnect to <strong>dynamic created databases</strong> by multiple users simultaneously.</em></p>