Rails group_by增加总和

时间:2015-12-14 16:10:23

标签: ruby-on-rails activerecord

我的应用程序中有User模型。他们属于季节模型。我想生成一个图表,其中包含季节用户注册的演变。例如:

 u.users.group_by_month("users.created_at").count

我使用gem groupdate来获取按月创建的用户数量,它的工作方式如下:

{Wed, 01 Jul 2015 00:00:00 BRT -03:00=>2, Sat, 01 Aug 2015 00:00:00 BRT -03:00=>0, Tue, 01 Sep 2015 00:00:00 BRT -03:00=>0, Thu, 01 Oct 2015 00:00:00 BRT -03:00=>0, Sun, 01 Nov 2015 00:00:00 BRST -02:00=>3}

这行结果如下:

u.users.group_by_month("users.created_at").count.inject({}) do 
   |cumulative, (date, total)|
   cumulative[date] = total + (cumulative.values.last || 0)
   cumulative
end

因此,它每月返回新用户的数量。太好了!

现在我想获得该月注册的用户总数。因此,如果第一个月有一个用户而第二个月有3个用户,那么它将显示[1,4]而不是[1,3]。我希望得到注册用户的演变。因此,对于当前月份,它将导致注册用户的总数。

在@jvnill的注入建议之后,我最终得到了:

i = 0
j = 0
loop = True
newList = []

while loop:
    try:
        i = myIntList.index(0, j)
        newList.append(myIntList[j:i])
        j = i + 1
    except ValueError as e:
        newList.append(myIntList[j:])
        loop = False

print newList
[[21, 22, 23, 24], [1, 2, 3], [1, 2, 3, 4, 5, 6, 7]]

但听起来有点黑客。还有更好的建议吗?

1 个答案:

答案 0 :(得分:1)

因为您已经拥有哈希中每个月的计数列表,其中键是月份,而值是每个月的总计,您可以迭代哈希并将累积总数保存在数组中。我不确定核心数组方法中是否有这样的快捷方式。

counts = u.users.group_by_month('users.created_at').count

counts.inject(0) do |sum, (date, total)|
  counts[date] = sum + total
end

p counts