将 Rails 3.1 与多个数据库连接 [英] Connecting Rails 3.1 with Multiple Databases

查看:31
本文介绍了将 Rails 3.1 与多个数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ShowNearby 上,我们一直在进行从 PHP 到 RoR 3.1 的大规模迁移,我们面临一些问题,你们中的一些人之前可能已经解决了这些问题.

At ShowNearby we have been doing a very big migration to RoR 3.1 from PHP and we are facing several problems that may be some of you have solved before.

我们有大量数据,我们决定将我们的数据库分成几个我们可以单独处理的数据库.比如我们的账号、地点、日志等被拆分成几个数据库

We have big amounts of data and we decided to segregate our DB into several DBs that we can handle separately. For example, our accounts, places, logs and others are split into several databases

我们需要得到迁移、装置、模型,才能很好地发挥作用,到目前为止,它已经相当混乱了.我们对可接受的解决方案的一些要求:

We need to get migrations, fixtures, models, to play nicely, and so far it has been quite messy. Some of our requirements for a solution to be acceptable:

  • 一个模型应该与其中一个数据库中的一个表相关.
  • rake db:drop - 应该删除我们在 database.yml 中指定的所有数据库环境
  • rake db:create - 应该创建我们在 database.yml 中指定的所有数据库环境
  • rake db:migrate - 应该运行到各种数据库的迁移
  • rake db:test - 应该抓取夹具并将它们放入各种数据库和测试单元/功能/等

我们正在考虑为每个数据库设置单独的 rails 项目并将它们与 ActiveResource 连接,但我们觉得这不是很有效.有没有人遇到过类似的问题?

We are considering setting separate rails projects per each database and connecting them with ActiveResource, but we feel this is not very efficient. Have any of you deal with a similar problem before?

推荐答案

对于 Wukerplank 的回答,您也可以像往常一样将连接详细信息放在 database.yml 中,名称如下:

To Wukerplank's answer, you can also put the connection details in database.yml like usual with a name like so:

log_database_production:
  adapter: mysql
  host: other_host
  username: logmein
  password: supersecret
  database: logs

然后在您的特殊模型中:

Then in your special model:

class AccessLog < ActiveRecord::Base
  establish_connection "log_database_#{Rails.env}".to_sym
end

防止那些讨厌的凭据出现在您的应用程序代码中.

To keep those pesky credentials from being in your application code.

如果你想在多个模型中重用这个连接,你应该创建一个新的抽象类并从它继承,因为连接与类紧密耦合(如这里此处此处),并且将为每个类创建新连接.

If you want to reuse this connection in multiple models, you should create a new abstract class and inherit from it, because connections are tightly coupled to classes (as explained here, here, and here), and new connections will be created for each class.

如果是这样,设置如下:

If that is the case, set things up like so:

class LogDatabase < ActiveRecord::Base
  self.abstract_class = true
  establish_connection "log_database_#{Rails.env}".to_sym
end

class AccessLog < LogDatabase
end

class CheckoutLog < LogDatabase
end

这篇关于将 Rails 3.1 与多个数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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