Til*_*dor 28 database activerecord ruby-on-rails
在我们的计划中,每个客户都有自己的数据库.我们通过电子邮件将他们连接到数据库的链接发送给他们.该链接包含一个GUID,使程序知道要连接到哪个数据库.
如何以动态和编程方式将ActiveRecord连接到正确的数据库?
Jim*_*uls 39
您也可以轻松完成此操作而无需对任何内容进行硬编码并自动运行迁移:
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)
Run Code Online (Sandbox Code Playgroud)
我发现之后在特定模型上重新建立旧连接很有用:
CustomerModel.establish_connection(spec)
Run Code Online (Sandbox Code Playgroud)
Til*_*dor 15
您可以通过调用ActiveRecord :: Base.establish_connection(...)随时更改与ActiveRecord的连接
IE:
ActiveRecord::Base.establish_connection({:adapter => "mysql", :database => new_name, :host => "olddev",
:username => "root", :password => "password" })
Run Code Online (Sandbox Code Playgroud)
And*_*edo 11
自从这个问题被创建以来已经有一段时间了,但我不得不说还有另一种方式:
conn_config = ActiveRecord::Base.connection_config
conn_config[:database] = new_database
ActiveRecord::Base.establish_connection conn_config
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19320 次 |
| 最近记录: |