<p>What is the best way to do per-user database connections in <code>Rails</code>? </p>

<p>I realize this is a poor Rails design practice, but we're gradually replacing an existing web application that uses one database per user. A complete redesign/rewrite is not feasible.</p>

[{'answer_id': 58767, 'author': 'changelog', 'author_id': 5646, 'author_profile': 'https://Stackoverflow.com/users/5646', 'pm_score': 1, 'selected': False, 'text': '<p>Take a look at <a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001397" rel="nofollow noreferrer">ActiveRecord::Base.establish_connection</a>. That\'s how you connect to a different database server. I can\'t be of much more help since I don\'t know how you recognize the user or map it to it\'s database, but I suppose a master database will have that info (and the connection info should be on the database.yml file).</p>\n\n<p>Best of luck.</p>\n'}, {'answer_id': 59063, 'author': 'Kevin Kaske', 'author_id': 2737, 'author_profile': 'https://Stackoverflow.com/users/2737', 'pm_score': 4, 'selected': True, 'text': '<p>Put something like this in your application controller. I\'m using the subdomain plus "_clientdb" to pick the name of the database. I have all the databases using the same username and password, so I can grab that from the db config file.</p>\n\n<p>Hope this helps!</p>\n\n<pre><code>class ApplicationController &lt; ActionController::Base\n\n  before_filter :hijack_db\n\n  def hijack_db\n    db_name = request.subdomains.first + "_clientdb"\n\n    # lets manually connect to the proper db\n    ActiveRecord::Base.establish_connection(\n      :adapter  =&gt; ActiveRecord::Base.configurations[ENV["RAILS_ENV"]][\'adapter\'],\n      :host     =&gt; ActiveRecord::Base.configurations[ENV["RAILS_ENV"]][\'host\'],\n      :username =&gt; ActiveRecord::Base.configurations[ENV["RAILS_ENV"]][\'username\'],\n      :password =&gt; ActiveRecord::Base.configurations[ENV["RAILS_ENV"]][\'password\'],\n      :database =&gt; db_name\n    )\n  end\nend\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/58755', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/624/']