如何在 Ruby on Rails 中动态更改所有模型的 Active Record 数据库? [英] How can I dynamically change the Active Record database for all models in Ruby on Rails?

查看:28
本文介绍了如何在 Ruby on Rails 中动态更改所有模型的 Active Record 数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In our program, each customer gets their own database. We e-mail them a link that connects them to their database. The link contains a GUID that lets the program know which database to connect to.

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

How do I dynamically and programatically connect ActiveRecord to the right db?

推荐答案

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

You can also do this easily without hardcoding anything and run migrations automatically:

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)

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

I find it useful to re-establish the old connection on a particular model afterwards:

CustomerModel.establish_connection(spec)

这篇关于如何在 Ruby on Rails 中动态更改所有模型的 Active Record 数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆