【问题标题】:Ruby ActiveRecord Dynamic Model creationRuby ActiveRecord 动态模型创建
【发布时间】:2012-03-29 06:45:32
【问题描述】:

我正在尝试与 ActiveRecord 建立多数据库连接。目前我需要将数据插入到总共 2 个数据库中。 No.Of 数据库有可能增加。

所以我动态创建了 2 个类,它们将从 ActiveRecord::Base 扩展

Object.const_set("Connection1",Class.new(ActiveRecord::Base) do
  self.abstract_class = true
  self.establish_connection({
    :host=>"localhost", :username=>"root", :password=>"root", :database=>"db1", :encoding=>"utf8", :adapter=>"mysql2"})
end)

Object.const_set("Connection2",Class.new(ActiveRecord::Base) do
  self.abstract_class = true
  self.establish_connection({
    :host=>"localhost", :username=>"root", :password=>"root", :database=>"db2", :encoding=>"utf8", :adapter=>"mysql2"})
end)

然后我创建了相应的从每个类扩展的动态模型

Object.const_set("ConnectionUser1",Class.new(Connection1) do
  self.table_name = 'user'
  def self.foo
    all.count
  end
end)

Object.const_set("ConnectionUser2",Class.new(Connection2) do
  self.table_name = 'user'
  def self.foo
    all.count
  end
end)

然后当我尝试调用 foo 方法时

p ConnectionUser1.foo
p ConnectionUser2.foo

它给了我 ActiveRecord::ConnectionNotEstablished 错误。

我听说如果模型没有连接,ActiveRecord 会连接它们的父节点

所以根据这个ConnectionUser1应该使用Connection1的连接,ConnectionUser2使用Connection2的连接。

那为什么ActiveRecord建立连接失败?

任何帮助将不胜感激。
谢谢。

【问题讨论】:

    标签: ruby activerecord multiple-databases


    【解决方案1】:

    看看下面的链接,它显示了如何使用 ActiveRecord 使用多个数据库。

    How do i work with two different databases in rails with active records?

    【讨论】:

      猜你喜欢
      • 2017-08-07
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      相关资源
      最近更新 更多