【问题标题】:How to best handle per-Model database connections with ActiveRecord?如何使用 ActiveRecord 最好地处理每个模型的数据库连接?
【发布时间】:2010-09-13 13:28:53
【问题描述】:

我想要规范的方式来做到这一点。我的 Google 搜索不足。我有一个 ActiveRecord 模型,它应该映射到与应用程序的其余部分不同的数据库。我也想将新配置存储在 database.yml 文件中。

我知道应该调用建立连接,但不清楚在哪里。这是我到目前为止得到的,但它不起作用:

class Foo < ActiveRecord::Base
    establish_connection(('foo_' + ENV['RAILS_ENV']).intern)
end

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    另外,对使用不同数据库的模型进行子类化是个好主意,例如:

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

    在你的模型中

    class Foo < AnotherBase
    end
    

    当您需要添加访问相同的另一个数据库的后续模型时,它很有用。

    【讨论】:

      【解决方案2】:

      呵呵。我是对的!更干净:

      class Foo < ActiveRecord::Base
          establish_connection "foo_#{ENV['RAILS_ENV']}"
      end
      

      很棒的帖子at pragedave.pragprog.com

      【讨论】:

        猜你喜欢
        • 2015-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-04
        • 1970-01-01
        • 1970-01-01
        • 2014-05-31
        • 1970-01-01
        相关资源
        最近更新 更多