好的,所以我有
>> 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]]
问题是我有几个Sun,1月9日和一对夫妇10日,而不是像这样的一个
这就是我需要的
=> [[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]]
答案 0 :(得分:21)
Time
是一个非常复杂的分组对象。假设您希望按创建日期进行分组,而不是完整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
答案 1 :(得分:17)
我认为这是一个更加优雅和简单的解决方案
list.group_by{|x| x.created_at.strftime("%Y-%m-%d")}
答案 2 :(得分:8)
有一个宝石:groupdate。
用法(来自文档):
User.group_by_day(:created_at).count
# {
# 2013-04-16 00:00:00 UTC => 50,
# 2013-04-17 00:00:00 UTC => 100,
# 2013-04-18 00:00:00 UTC => 34
# }
答案 3 :(得分:3)
Ipsum的回答实际上很好,可能是最好的:
在Arel:
requests = Arel::Table.new(:requests)
query = requests.project("COUNT(*), CAST(requests.created_at AS DATE) as created_at")
query = query.group("CAST (requests.created_at AS DATE)")
Request.find_by_sql(query.to_sql)
答案 4 :(得分:1)
没有额外宝石的小组:
def self.group_by_day items
data = items.group_by{|x| x.created_at.to_date}
chart_data = {}
data.each do |a,b|
chart_data.merge!({a => b.count})
end
return chart_data
end
答案 5 :(得分:1)
你可以在MySQL中使用GROUP BY DATE(created_at)
关于ruby代码,你可以像这样使用
list.group('DATE(created_at)').map {|k,v| [k, v.length]}.sort