使用Active Record Base Connection从多个服务器中提取数据

时间:2015-08-12 16:24:48

标签: postgresql ruby-on-rails-4 activerecord

我有一个小型的Rails 4.2应用程序,它基本上是一个美化的指标应用程序。我希望能够基于几种类方法创建度量标准记录。

问题是,我需要将数据从多个生产服务器提取到这个服务器中,而且我不确定如何使用AR Base Connection来实现这一点。

以下是度量标准类中的目标(度量服务器)方法:

class Metric < ActiveRecord::Base

  def self.last_year_mtd
    m = Metric.new
    m.agency_name = Figaro.env.agency_name
    m.metric_type = "Last Year MTD"
    sql = ActiveRecord::Base.connection.execute("select sum(dst_amt::DECIMAL) from distributions where dst_code like 'COL%' and dst_posted_date::DATE BETWEEN (select (date_trunc('month', current_date)) - INTERVAL '13 Month') and (select (date_trunc('month', current_date)) - INTERVAL '366 Day')")
    total = sql[0]["sum"].to_s
    m.amount = total
    m.save
  end

  def self.last_month
    m = Metric.new
    m.agency_name = Figaro.env.agency_name
    m.metric_type = "Last Month"
    sql = ActiveRecord::Base.connection.execute("select sum(dst_amt::DECIMAL) from distributions where dst_code like 'COL%' and dst_posted_date::DATE BETWEEN (select (date_trunc('month', current_date)) - INTERVAL '1 Month') and (select date_trunc('month', now())::date - 1)")
    total = sql[0]["sum"].to_s
    m.amount = total
    m.save
  end

  def self.current_month
    m = Metric.new
    m.agency_name = Figaro.env.agency_name
    m.metric_type = "Current Month"
    sql = ActiveRecord::Base.connection.execute("select sum(dst_amt::DECIMAL) from distributions where dst_code like 'COL%' and dst_posted_date::DATE BETWEEN (select (date_trunc('month', current_date))) and NOW()::DATE")
    total = sql[0]["sum"].to_s
    m.amount = total
    m.save
  end
end

因此,当我构建此类并在源服务器(我试图从中提取指标)中对其进行测试时,所有这些方法都能正常工作并创建指标,因为我从本地提取数据库中。

问题是我有8个生产服务器从中提取数据,执行SQL并从中创建记录。

我如何在公制服务器上执行此操作。我假设我需要在database.yml中设置所有8个服务器的postgres信息,并将它们命名为每个独特的东西(如acme,johnson,joe等)。但是在我的类和方法中,如何使用块调用所有8个服务器并对每个服务器进行迭代,为每个服务器创建新的度量标准记录并将其存储到本地度量模型/数据库?

我对AR摘要模糊不清,所以我不确定这是否是我需要的,或者是否有一种更简单的方法可以做到这一点我在研究中没有看到

提前感谢您提供的任何建议。

1 个答案:

答案 0 :(得分:0)

我能够通过阅读本月早些时候发布的这篇文章并使用抽象的AR模型来促进与报告/度量服务器的通信来解决这个问题。

Getting Information from another Rails Server