如何使查询更简单?

时间:2018-07-06 23:01:11

标签: ruby-on-rails

我正在创建Rails 5应用程序。 在这个应用程序中,我有一个从子对象获取值并将其添加到哈希中的方法。下面的方法/代码可以很好地工作,但是我该如何在速度和结构上使其更好呢?

def generated_values(period, year, month, quarter)
        count = 0
        score = 0
        actual = 0
        goal = 0
        red = 0
        if stype == "measure"
            measures.period(period, year, month, quarter).each do |measure|
                count += 1
                score += measure.score
                actual += measure.value_actual
                goal += measure.value_goal
                red += measure.value_redflag
            end
        elsif stype == "objective"
            children.each do |child|
                child.measures.period(period, year, month, quarter).each do |measure|
                    count += 1
                    score += measure.score
                    actual += measure.value_actual
                    goal += measure.value_goal
                    red += measure.value_redflag
                end
            end
        elsif stype == "scorecard"
            children.each do |child|
                child.children.each do |child2|
                    child2.measures.period(period, year, month, quarter).each do |measure|
                        count += 1
                        score += measure.score
                        actual += measure.value_actual
                        goal += measure.value_goal
                        red += measure.value_redflag
                    end
                end
            end 
        end
        values = { :score => score == 0 ? 0 : (score / count).round, :actual => actual, :goal => goal, :red => red }
    end

1 个答案:

答案 0 :(得分:0)

我想我会做类似的事情:

def generated_values(period, year, month, quarter)

  case stype
  when "measure"
    selected_measures = measures
  when "objective"
    selected_measures = child_measures
  when "scorecard"
    selected_measures = grandchild_measures
  end

  count = selected_measures.count

  {
    score:  count > 0 ? (selected_measures.sum(:score)/count).round : 0,
    actual: selected_measures.sum(:value_actual)
    goal:   selected_measures.sum(:value_goal) 
    red:    selected_measures.sum(:value_redflag)
  }

end

未经测试且即席即用。

自然,最有趣的部分是selected_measures =位。但是,您没有提供足够的信息来帮助正确制定这些查询。