如何在Ruby on Rails中为所有模型动态更改Active Record数据库?

在我们的计划中,每个客户都有自己的数据库。 我们通过电子邮件发送链接,将它们连接到数据库。 该链接包含一个GUID,使程序知道要连接到哪个数据库。

如何以动态和编程方式将ActiveRecord连接到正确的数据库?

您也可以轻松完成此操作而无需对任何内容进行硬编码并自动运行迁移:

customer = CustomerModel.find(id) spec = CustomerModel.configurations[RAILS_ENV] new_spec = spec.clone new_spec["database"] = customer.database_name ActiveRecord::Base.establish_connection(new_spec) ActiveRecord::Migrator.migrate("db/migrate_data/", nil) 

我发现之后在特定模型上重新建立旧连接很有用:

 CustomerModel.establish_connection(RAILS_ENV) 

您可以通过调用ActiveRecord :: Base.establish_connection(…)随时更改与ActiveRecord的连接

IE:

  ActiveRecord::Base.establish_connection({:adapter => "mysql", :database => new_name, :host => "olddev", :username => "root", :password => "password" }) 

这个问题已经创建了一段时间了,但我不得不说还有另一种方法:

 conn_config = ActiveRecord::Base.connection_config conn_config[:database] = new_database ActiveRecord::Base.establish_connection conn_config 
 class Database def self.development! ActiveRecord::Base.establish_connection(:development) end def self.production! ActiveRecord::Base.establish_connection(ENV['PRODUCTION_DATABASE']) end def self.staging! ActiveRecord::Base.establish_connection(ENV['STAGING_DATABASE']) end end 

.env (例如使用dotenv-rails gem):

 PRODUCTION_DATABASE=postgres://... STAGING_DATABASE=postgres://... 

现在你可以:

 Database.development! User.count Database.production! User.count Database.staging! User.count # etc.