Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 289
Alan Hecht Avatar asked Sep 12 '08 11:09

Alan Hecht


2 Answers

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
like image 163
Kevin Kaske Avatar answered Sep 28 '22 08:09

Kevin Kaske


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.

like image 43
changelog Avatar answered Sep 28 '22 08:09

changelog