【问题标题】:Multiple DB connection in rails导轨中的多个 DB 连接
【发布时间】:2011-09-14 14:22:53
【问题描述】:

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

发展:

 adapter: mysql
 username: root
 password: 
 database: example_development

私人:

adapter: mysql
username: root
password: 
database: example_private_development

可以使用建立连接 :private 进行连接

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

请帮我清除它。

【问题讨论】:

    标签: mysql ruby-on-rails database ruby-on-rails-3


    【解决方案1】:

    试试

    rake db:create:all
    

    是的,Rails 应用程序中可以有多个数据库连接。

    这是我曾经做过的,我创建了两个继承自ActiveRecord::Base 的类,并在这些类中设置了连接。

    然后我在其中一个类中继承了我的所有模型,而不是直接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 数据库的模型:

    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
    

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

    class School < Test1Base
      #code
    end
    
    class Student < Test2Base
      #code
    end
    

    【讨论】:

    • 嗨 sameera ,您的回答是正确的。我还有一个问题如何为“portal_development”迁移模型。帮帮我...
    • 嗨@Shamith,哎呀,这是一个错字,那应该是环境名称,我已经编辑了上面的database.yml,因为我以我现有的文件为例忘记删除一些行,对不起...:D
    【解决方案2】:

    感谢回复。

    我们可以为特定数据库迁移模型,例如

    db:migrate RAILS_ENV="portal_development"'.

    还有更多与 DB 建立连接的变化。检查下面的更正

    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
    

    感谢 sameera 的宝贵回复。

    干杯

    沙米特 c

    【讨论】:

      【解决方案3】:

      可能使用active_delegatehttp://railslodge.com/plugins/595-active-delegate

      【讨论】:

        猜你喜欢
        • 2011-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-22
        • 1970-01-01
        • 2016-12-13
        相关资源
        最近更新 更多