【问题标题】:Ruby on Rails iterate through column efficientlyRuby on Rails 高效地遍历列
【发布时间】:2019-11-08 14:46:49
【问题描述】:
            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,然后对每个唯一条目重复。

我在下面包含的代码确实可以工作并生成所需的输出,但它的速度很慢,而且读取到数据库中的数据越多,速度就越慢。

它会创建一个哈希值并输入到 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 完成繁重的工作,而不是在 rails 中进行计算,但我不确定如何解决这个问题。

感谢您的帮助。

【问题讨论】:

  • SQL 查询类似于'select iteration,sum(group_hits_per_iteration) as Iterations From someTable group by iteration
  • 这看起来像XY Problem。您根本不应该遍历列 - 高效或以其他方式。您应该使用查询。

标签: sql ruby-on-rails


【解决方案1】:

如果您只想获得每次迭代的总和,以下代码应该可以工作:

# 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,我采用了最低日期

【讨论】:

  • 谢谢,这真的很有帮助。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2012-08-21
  • 2014-02-07
  • 1970-01-01
  • 2015-07-19
  • 1970-01-01
  • 2022-12-11
  • 2010-10-11
  • 2022-01-23
相关资源
最近更新 更多