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

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

问题描述

好,所以我有

 >> list = Request.find_all_by_artist(someBand)
=> [#< Request id:1,artist:someBand,歌曲:someSong,地点:Knebworth - Stevenage,英国,显示日期:2011-07-01,金额:nil,user_id: 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,2011年1月9日18:34:19 UTC +00:00,1],[Sun,2011年1月9日18:38 :48 UTC +00:00,1],[Sun,2011年1月9日18:51:10 UTC +00:00,1],[Sun,2011年1月9日18:52:30 UTC +00:00,1] ,[星期四,10二月2011 02:22:08 UTC +00:00,1],[星期四,2011年2月10日20:02:20 UTC +00:00,1]]

问题是我有几个Sun,09年1月和第10个,而不是像这样的一个



这是我需要的

  => [[Sat,01 Jan 2011 18:14:08 UTC +00:00,10],[Sun,2011年1月9日18:34:19 UTC +00:00,4],[星期四,2011年2月10日20:02 :20 UTC +00:00,2]] 


解决方案

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



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

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

然后,按该方法分组。

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


ok so i have

 >> 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".............

and then

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]]

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

this is what i need

=> [[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 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天全站免登陆