我怎样才能动态改变在Ruby on Rails的所有型号的活动记录数据库? [英] How can I dynamically change the Active Record database for all models in Ruby on Rails?

查看:133
本文介绍了我怎样才能动态改变在Ruby on Rails的所有型号的活动记录数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的程序中,每个客户得到自己的数据库。我们的E-MAIL他们,他们连接到他们的数据库的链接。该链接包含一个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(RAILS_ENV)

这篇关于我怎样才能动态改变在Ruby on Rails的所有型号的活动记录数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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