What is the best way to connect to the database for each user in Rails

What is the best way to connect to the database for each user in Rails ?

I understand this is a bad Rails design practice, but we are gradually replacing an existing web application that uses one database for each user. A complete redesign / rewriting is not possible.

+6
ruby-on-rails
source share
2 answers

Put something like this in your application controller. I use the subdomain plus "_clientdb" to select the database name. I have all the databases using the same username and password, so I can get this from the db configuration 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 
+10
source share

Take a look at ActiveRecord :: Base.establish_connection . This is how you connect to another database server. I can’t get any more help since I don’t know how you recognize the user or map it to the database, but I believe that the main database will have this information (and the connection information should be in the database.yml file) .

Good luck.

+1
source share

All Articles