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

问题描述 投票:0回答:4

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

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

ruby-on-rails database activerecord
4个回答
41
投票

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

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(spec)

16
投票

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

即:

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

14
投票

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

conn_config = ActiveRecord::Base.connection_config.to_h.deep_dup
conn_config[:database] = new_database
ActiveRecord::Base.establish_connection conn_config

2
投票
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
宝石):

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

现在您可以:

Database.development!
User.count
Database.production!
User.count
Database.staging!
User.count
# etc.
© www.soinside.com 2019 - 2024. All rights reserved.