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