views:

255

answers:

2

What is the best way to do per-user database connections in Rails?

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.

+1  A: 

Take a look at ActiveRecord::Base.establish_connection. 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).

Best of luck.

changelog
+5  A: 

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.

Hope this helps!

class ApplicationController < ActionController::Base

  before_filter :hijack_db

  def hijack_db
    db_name = request.subdomains.first + "_clientdb"

    # lets manually connect to the proper db
    ActiveRecord::Base.establish_connection(
      :adapter  => ActiveRecord::Base.configurations[ENV["RAILS_ENV"]]['adapter'],
      :host     => ActiveRecord::Base.configurations[ENV["RAILS_ENV"]]['host'],
      :username => ActiveRecord::Base.configurations[ENV["RAILS_ENV"]]['username'],
      :password => ActiveRecord::Base.configurations[ENV["RAILS_ENV"]]['password'],
      :database => db_name
    )
  end
end
Kevin Kaske