简体   繁体   English

在 Rails 中进行每用户数据库连接的最佳方法是什么

[英]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.

相关问题 每个用户的最佳参数的最佳做法? - Best practice for per-user strong parameters? 有关每个用户设置和预定义选项的最佳做法 - Best practices regarding per-user settings and predefining options 使用设计和轨道时,基于每个用户设置区域设置3 - Setting locale on a per-user basis when using devise and rails 3 在 Rails 3 中处理每个用户设置的最佳方法 - Best way to handle per user Settings in Rails 3 接收所有当前用户 ActionCable 连接的最佳方式是什么? - What is the best way to receive all current user ActionCable connections? 使用Devise for Rails使用每用户“maximum_attempts”值锁定用户 - Locking a user using a per-user `maximum_attempts` value with Devise for Rails 在Rails中为数据库设定种子的最佳方法是什么? - What is the best way to seed a database in Rails? 为Ruby on Rails设计数据库的最佳方法是什么? - What is the best way to design database for Ruby on Rails? 在Rails中实现用户登录的最佳方法是什么? - What is the best way to implement user login in Rails? 如何为Rails中的第三方集成建模/关联每个用户的配置设置? - How to model/associate per-user configuration settings for third-party integrations in Rails?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM