[英]Ruby on Rails iterate through column efficiently
created_at iteration group_hits_per_iteration
--------------------------------------------------------------------
2019-11-08 08:14:05.170492 300 34
2019-11-08 08:14:05.183277 300 24
2019-11-08 08:14:05.196785 300 63
2019-11-08 08:14:05.333424 300 22
2019-11-08 08:14:05.549140 300 1
2019-11-08 08:14:05.576509 300 15
2019-11-08 08:44:05.832730 301 69
2019-11-08 08:44:05.850111 301 56
2019-11-08 08:44:05.866771 301 18
2019-11-08 08:44:06.310749 301 14
您好我的目标是为“迭代列”中的每个唯一值创建“group_hits_per_iteration”中的值的总和,然后使用 chartkick 绘制图形。
例如,对于第 300 次迭代,我会将 34、24、63、22、1、15 加起来总共 159,然后对每个唯一条目重复。
我在下面包含的代码确实可以工作并生成所需的 output 但它很慢,并且读取到数据库中的数据越多越慢。
它会创建一个 hash 并输入到 chartkick。
hsh = {}
Group.pluck(:iteration).uniq.each do |x|
date = Group.where("iteration = #{x}").pluck(:created_at).first.localtime
itsum = Group.where("iteration = #{x}").pluck('SUM(group_hits_per_iteration)' )
hsh[date] = itsum
end
<%= line_chart [
{name: "#{@groupdata1.first.networkid}", data: hsh}
] %>
我正在寻找其他方法来解决这个问题,我正在考虑让 SQL 做繁重的工作,而不是在轨道上进行计算,但不确定如何解决这个问题。
谢谢您的帮助。
如果您只想获得每次迭代的总和,以下代码应该可以工作:
# new lines only for readability
group_totals =
Group
.select('iteration, min(created_at) AS created_at, sum(group_hits_per_iteration) AS hits')
.group('iteration')
.order('iteration') # I suppose you want the results in some order
group_totals.each do |group|
group.iteration # => 300
group.hits # => 159
group.created_at # => 2019-11-08 08:14:05.170492
end
在这种情况下,所有繁重的工作都由数据库完成,您只需在 ruby 代码中读取结果即可。
注意:在您的代码中,您为每次迭代都采用了第一个created_at
,我采用了最低日期
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.