【发布时间】:2017-08-12 15:35:20
【问题描述】:
我有一种方法可以输出以下用于图表的哈希格式。
# Monthly (Jan - Dec)
{
"john": [1,2,3,4,5,6,7,8,9,10,11,12],
"mike": [1,2,3,4,5,6,7,8,9,10,11,12],
"rick": [1,2,3,4,5,6,7,8,9,10,11,12]
}
# the indices represents the month
# e.g [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
# Index
# 0 = Jan
# 1 = Feb
# 2 = Mar
...
以下方法遍历给定年份内具有特定销售代表名称的所有商店发票并生成上述结果
def chart_data
hash = Hash.new {|h,k| h[k] = [] }
(1..12).each do |month|
date_range = "1/#{month}/#{date.year}".to_date.all_month
all_reps.each do |name|
hash[name] << store.bw_invoices.where(sales_rep_name: name,
purchase_date: date_range).sum(:subtotal).to_f
end
end
return hash
end
当我运行这个方法时,它需要 4~5 秒才能执行。我真的需要优化这个查询。我想出了两个我认为会有所帮助的解决方案,但我很想获得您的一些专业知识。
- 将其移至后台作业
- 执行 SQL 查询以进行优化(如果这是最佳的,我需要帮助)
非常感谢您的宝贵时间
【问题讨论】:
-
您还可以添加一些示例数据吗?
Reps.all.first(10)还有,date.year是从哪里来的? -
模型之间是如何连接的?
all_reps、store、bw_invoices是如何定义或来自的?span> -
@spickermann 商店 has_many 发票,all_reps 是发票内的列。我只是采摘和 uniq 来获取所有代表。我希望这会有所帮助
-
@Vlad 感谢您的回答,date.year 可能只是 Date.today.year。如果我的代表次数超过 10 次,会发生什么?因为我需要遍历所有这些
-
你在用postgresql吗?
标签: ruby-on-rails ruby postgresql loops ruby-on-rails-4