如何按天而不是按日期分组? [英] How do I group by day instead of date?

查看:28
本文介绍了如何按天而不是按日期分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我有

 >> list = Request.find_all_by_artist("someBand")
=> [#<Request id: 1, artist: "someBand", song: "someSong", venue: "Knebworth - Stevenage, United Kingdom", showdate: "2011-07-01", amount: nil, user_id: 2, created_at: "2011-01-01 18:14:08", updated_at: "2011-01-01 18:14:09".............

然后

list.group_by(&:created_at).map {|k,v| [k, v.length]}.sort
=> [[Sat, 01 Jan 2011 18:14:08 UTC +00:00, 10], [Sun, 09 Jan 2011 18:34:19 UTC +00:00, 1], [Sun, 09 Jan 2011 18:38:48 UTC +00:00, 1], [Sun, 09 Jan 2011 18:51:10 UTC +00:00, 1], [Sun, 09 Jan 2011 18:52:30 UTC +00:00, 1], [Thu, 10 Feb 2011 02:22:08 UTC +00:00, 1], [Thu, 10 Feb 2011 20:02:20 UTC +00:00, 1]]

问题是我有几个 1 月 9 日和 10 号的几个太阳,而不是像这样的一个

the problem is I have a few Sun, 09 Jan and a couple for the 10th, instead of one like this

这就是我需要的

=> [[Sat, 01 Jan 2011 18:14:08 UTC +00:00, 10], [Sun, 09 Jan 2011 18:34:19 UTC +00:00, 4], [Thu, 10 Feb 2011 20:02:20 UTC +00:00, 2]]

推荐答案

Time 是一个非常复杂的分组对象.假设您想按创建日期而不是完整的Time 进行分组,请开始在您的模型中创建自定义方法以返回分组条件.

Time is a quite complex object to group by. Assuming you want to group by the creation date, instead of the full Time, start creating a custom method in your model to return the group criteria.

该方法应该返回创建日期,可能是字符串.

The method should return the creation date, possibly as string.

def group_by_criteria
  created_at.to_date.to_s(:db)
end

然后,按那个方法分组.

Then, group by that method.

list.group_by(&:group_by_criteria).map {|k,v| [k, v.length]}.sort

这篇关于如何按天而不是按日期分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆