多轨数据库连接 [英] multiple database connection in rails

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

问题描述

我希望我的Entry模型能够使用多个数据库。当客户加入网络时,会自动为该客户创建一个新数据库。其他模型将使用相同的数据库。这可能在铁轨?

解决方案

有趣的是,我只是在十分钟前提出了一个解决方案......



这里有...

首先在你的database.yml中定义单独的数据库连接

我的

 制作:
适配器:mysql
-etc etc-

然后我又添加了一个(对于我来说,我有一个我想连接的遗留数据库... )

  legacy_production:
适配器:mysql
-etc etc-

在适当的环境下重复执行此操作

接下来我要做的就是创建'lib'中一个名为'legacy_model.rb'的新文件,它看起来很简单,就像这样

  require'active_record'

class LegacyModel< ActiveRecord :: Base
self.abstract_class = true
establish_connectionlegacy _#{RAILS_ENV}
end

现在,为了利用这个,我只是创建一个类/模型,并像LegacyModel一样继承...

  class User< LegacyModel 
-any验证等你可能想要的 -
结束

它会访问遗留数据库而不是我正在使用的数据库。



可能有更好的解决方案,但这似乎适用于我 - 希望它有帮助! / p>

I want my Entry model to use multiple databases. When a customer joins the network a new database is automaticly created for this customer. Other models will use same database. Is this possible in rails?

解决方案

Funny, I just came up with a solution to this ten minutes ago...

Here goes...

First off define the separate database connection in your database.yml

mine has

production:
 adapter: mysql
 -etc etc-

Then I added an additional one (for me, I've a legacy database I want to connect to...)

legacy_production:
  adapter: mysql
  -etc etc-

Repeat this for different environments where appropriate

The next thing I did was create a new file in 'lib' called 'legacy_model.rb' and it looks quite simply like this

 require 'active_record'

    class LegacyModel < ActiveRecord::Base
      self.abstract_class = true
      establish_connection "legacy_#{RAILS_ENV}"
    end

Now, to make use of this, I just create a class/model and inherit from LegacyModel like so...

class User < LegacyModel
  -any validations etc you might want-
end

And voila, it'll access the legacy database instead of the one I'm using.

There are probably better solutions, but this seems to work for me - hope it helps!

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

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