[英]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.