简体   繁体   English

轨道中的多个DB连接

[英]Multiple DB connection in rails

I am trying to connect multiple database in ROR application.My database.yml is look like this in your database.yml file 我正在尝试连接ROR应用程序中的多个数据库。我的database.yml在您的database.yml文件中看起来像这样

development: 发展:

 adapter: mysql
 username: root
 password: 
 database: example_development

private: 私人的:

adapter: mysql
username: root
password: 
database: example_private_development

It is possible to connect using establish_connection :private 可以使用establish_connection:private进行连接

My doubt is that how use rake db:create.I am not able get solution from google. 我怀疑是如何使用rake db:create。我无法从谷歌获得解决方案。

Please help me to clear it. 请帮我清除它。

Try 尝试

rake db:create:all

And yes, it's possible to have multiple db connections in a Rails application. 是的,在Rails应用程序中可以有多个数据库连接。

This is what I did once, I have created two classes which inherit from ActiveRecord::Base and set the connections inside those classes. 这就是我曾经做过的,我创建了两个继承自ActiveRecord::Base类,并在这些类中设置连接。

Then I inherited all my models in one of those classes instead of direct ActiveRecord 然后我继承了其中一个类中的所有模型而不是直接的ActiveRecord

Below is an example: 以下是一个例子:

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

Then I have two models for both test1 and test2 databases: 然后我有test1和test2数据库的两个模型:

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

Thanks for reply. 谢谢你的答复。

we can migrate a model for particular DB, for example 例如,我们可以迁移特定数据库的模型

db:migrate RAILS_ENV="portal_development"' . db:migrate RAILS_ENV="portal_development"'

And more change for establishing connection with DB.check the corrected below 与DB.check建立连接的更多更改已在下面更正

class Test1Base < ActiveRecord::Base
  self.abstract_class = true
  establish_connection :development
end

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

Thanks sameera for your valuable reply. 同样感谢您的宝贵回复。

cheers 干杯

Shamith c 沙米斯c

Possibly use active_delegate ? 可能使用active_delegate http://railslodge.com/plugins/595-active-delegate http://railslodge.com/plugins/595-active-delegate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM