【问题标题】:more than one database per model每个模型有多个数据库
【发布时间】:2011-06-11 00:02:45
【问题描述】:
class Service < ActiveRecord::Base

establish_connection(
  :adapter  => "mysql",
  :host     => "myip",
  :username => "myusername",
  :password => "mypassword",
  :database => "mydatabase"
)

end

这行得通

Service.all #connects to mydatabase

但我需要这样的东西。

Service.use(mydatabase1).all #connects to mydatabase1
Service.use(mydatabase2).all #connects to mydatabase2

我怎样才能做到这一点?

更新

数据库名称是动态的。我希望服务模型动态连接数据库。 当我输入Service.use(weeweweaszxc).all 时,它必须使用weeweweaszxc 数据库。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    试着看看这里的这个问题。 How to best handle per-Model database connections with ActiveRecord?

    他们像往常一样在 database.yml 文件中定义数据库,并在模型中调用它:

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

    使用来自Priit's answer的信息

    【讨论】:

    • 如何在活动记录查询中选择数据库
    • 但模型连接的数据库是可变的
    • 在您的 database.yml 中定义数据库并在 establish_connection 调用中使用该名称。您想每个模型使用多个数据库吗?
    • 致电service.establish_connection("DB NAME"),然后致电service.all
    • 没问题,希望你的应用顺利
    猜你喜欢
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    相关资源
    最近更新 更多