使用Rails在Postgres中开发自定义函数

时间:2014-03-13 17:45:15

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

假设我有一个很大的复合公式来计算小部件的质量

quality = 0.4(factory_quality) + 0.3(1/days_since_manufacture) + 0.3(materials_quality)

这三个因素中的每一个都是函数本身,它们需要连接到工厂表,也可能是物料清单连接表与材料,其中相关记录是平均的或其他什么。

在架构上,你如何在Rails项目中管理它?什么是最好的做法:a)产生正确的查询和b)管理Rails中的代码?

目前对于sql,我在FROM语句中使用子查询:

SELECT *,
  (0.4 * factory_quality + 0.3 * (1/days_since_manufacture) + 0.3 * materials_quality) AS quality
FROM (
  SELECT *,
    ((factories.last_inspection_score + factories.variance_score)/2) AS factory_quality,
    (now() - widgets.created_at) AS days_since_manufacture,
    SUM(materials.quality_score) AS materials_quality
  FROM widgets,
  JOIN factories ON widget.factory_id = factories.id
  JOIN bills_of_materials ON widget.id = bills_of_materials.widget_id
  JOIN materials ON bills_of_materials.material_id = materials.id
  GROUP BY widgets.id
) AS widgets;

在rails中,我主要使用ActiveRecord实现:

class Widget < ActiveRecord::Base
  belongs_to :factory
  has_many :bills_of_material
  has_many :materials, through :bills_of_material

  class << self
    def with_quality
      select([
        "widgets.*",
        "(0.4 * factory_quality + 0.3 * (1/days_since_manufacture) + 0.3 * materials_quality) AS quality"
      ].join(",")
      .from("(#{subquery}) AS widgets")
    end
    private
      def subquery
        select([
          "widgets.*",
          "((factories.last_inspection_score + factories.variance_score)/2) AS factory_quality",
          "(now() - widgets.created_at) AS days_since_manufacture",
          "SUM(materials.quality_score) AS materials_quality"
        ].join(","))
        .joins(:factory,:materials)
        .group("widgets.id")
        .to_sql
      end
  end
end

那就是说,我觉得我可以把它变成Postgres中的自定义函数,将所有这些sql移入该函数,迁移它,并清理轨道看起来像

def with_scores
  select("*,quality_score_func(id) AS quality")
end

或类似的东西,但我觉得通过数据库迁移管理将成为一个不断发展的公式将是一件痛苦的事情,更不用说找出当前形式的公式的一些任务是(也很难测试)。

其他人如何解决这个问题?有任何提示或建议吗?

1 个答案:

答案 0 :(得分:2)

这是我能想到的最简单的SQL方法。我无法对此进行测试,但希望它至少是一项有益的练习。据我了解,如果您使用includes,Rails会将连接组合在一起,并将所有相关数据加载到一个查询中。

# All of these are additional Widget instance methods; you decide if they are private
#
# Example use:
#
#   @widget = Widget.includes(:factory, :materials).find(1)
#   puts @widget.quality_score
# or
#   @widgets = Widget.includes(:factory, :materials).all
#   @widgets.each { |widget| puts widget.quality_score }

# Consider making these weights named constants
def quality_score
  0.4 * factory_quality + \
  0.3 * (1/days_since_manufacture) + \
  0.3 * (materials_quality_score )
end

def days_since_manufacture
  Time.now - created_at
end

def factory_quality
  (factory.last_inspection_score + factory.variance_score)/2
end

def materials_quality_score
  materials.inject(0) {|sum, material| sum + material.quality_score }
end