title: Can I have thread safe per-request configuration for database connection and table_name in ActiveRecord (or Mongoid)?
body: <p>Also known as the &lt;&lt;"User has many Databases" question.>>  </p>
  
  <p><strong>The environment</strong></p>
  
  <p>My app is modeled like so:  </p>
  
  <pre><code>user has_many databases  
  database has_many tables  
  table has_many rows  
  row habtm(+value) columns   
  </code></pre>
  
  <p>you get the idea!  </p>
  
  <p>So instead of modelling a database <em>inside</em> a database,
  I would like to have: </p>
  
  <ul>
  <li>a sqlite3 database that holds the users and</li>
  <li>many sqlite databases for each user</li>
  </ul>
  
  <p>Each user will LCRUD his tables in his databases (similar to phpmyadmin)</p>
  
  <p><strong>The problem</strong>  </p>
  
  <p>I would like to have <em>thread safe</em> per-request configuration for
  database connection and table_name</p>
  
  <pre><code>class Table &lt; ActiveRecord::Base
  end
  
  # in some controller
  # set the connection to the user-selected database from some DB list
  Table.connection = current_user.session.connection
  # set the name to the user-selected table from some tables list
  Table.table_name = params[:table_name]
  @rows = Table.all #display them
  </code></pre>
  
  <p>EDIT<br>
  As you see, the connection is global and shared between threads, but as per my app's specs, each user has it's own connection. Now imagine that 2 different users make 2 requests at the same time.</p>
  
  <p><strong>The options?</strong></p>
  
  <ul>
  <li>I give up ActiveRecord and use bare-bones DB driver</li>
  <li>I give up thread saftey</li>
  </ul>