[英]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
?在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.我意识到这是一种糟糕的 Rails 设计实践,但我们正在逐步替换现有的 web 应用程序,该应用程序每个用户使用一个数据库。 A complete redesign/rewrite is not feasible.完全重新设计/重写是不可行的。
Put something like this in your application controller.在您的应用程序 controller 中添加类似的内容。 I'm using the subdomain plus "_clientdb" to pick the name of the database.我正在使用子域加上“_clientdb”来选择数据库的名称。 I have all the databases using the same username and password, so I can grab that from the db config file.我所有的数据库都使用相同的用户名和密码,所以我可以从 db 配置文件中获取它。
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
Take a look at ActiveRecord::Base.establish_connection .看看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).我无法提供更多帮助,因为我不知道您如何识别用户或 map 到它的数据库,但我想主数据库将具有该信息(并且连接信息应该在 database.yml 文件中)。
Best of luck.祝你好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.