Rails中的多个数据库连接 [英] Multiple DB connection in rails

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

问题描述

我正在尝试在ROR应用程序中连接多个数据库.我的database.yml看起来像这样 在您的database.yml文件中

I am trying to connect multiple database in ROR application.My database.yml is look like this in your database.yml file

发展:

 adapter: mysql
 username: root
 password: 
 database: example_development

私人:

adapter: mysql
username: root
password: 
database: example_private_development

可以使用Establishment_connection:private

It is possible to connect using establish_connection :private

我的疑问是如何使用rake db:create.我无法从Google获得解决方案.

My doubt is that how use rake db:create.I am not able get solution from google.

请帮助我清除它.

推荐答案

尝试

rake db:create:all

是的,在Rails应用程序中可能有多个数据库连接.

And yes, it's possible to have multiple db connections in a Rails application.

这是我曾经做过的事情,我创建了两个从ActiveRecord::Base继承的类,并在这些类内设置了连接.

This is what I did once, I have created two classes which inherit from ActiveRecord::Base and set the connections inside those classes.

然后,我继承了那些类之一中的所有模型,而不是直接的ActiveRecord

Then I inherited all my models in one of those classes instead of direct ActiveRecord

下面是一个示例:

database.yml file

#app uses two database
#1 - test1
#2 - test2
test1:
  adapter: mysql
  encoding: utf8
  database: test1
  username: root 
  password: xxx
  host: localhost

test2:
  adapter: mysql
  encoding: utf8
  database: test2
  username: root
  password: xxx
  host: localhost

然后我有两个用于test1和test2数据库的模型:

Then I have two models for both test1 and test2 databases:

class Test1Base < ActiveRecord::Base
    self.abstract_class = true
    establish_connection("test1")
end

class Test2Base < ActiveRecord::Base
  # No corresponding table in the DB.
  self.abstract_class = true
  establish_connection("test2")
end

然后我根据数据库继承我的模型:

Then I inherit my models according to database:

class School < Test1Base
  #code
end

class Student < Test2Base
  #code
end

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

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