Ruby-on-rails 按周/月/等和 ActiveRecord 分组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/902974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Grouping by week/month/etc & ActiveRecord?
提问by teich
I'm doing some statics calculation in my product. A user has performed a number of operations, let's say posted comments. I want to be able to show them how many comments they've posted per week for the past month, or per month for the past year.
我正在我的产品中进行一些静力学计算。用户执行了许多操作,比如说发表评论。我希望能够向他们展示他们过去一个月每周或过去一年每月发布的评论数量。
Is there any way with activerecord to group this way? Is my best best to simply do this manually - to iterate over the records summing based on my own criteria?
activerecord 有没有办法以这种方式分组?我最好是简单地手动执行此操作 - 根据我自己的标准迭代记录总和?
class User < ActiveRecord::Base
has_many :comments
end
class Comments < ActiveRecord::Base
belongs_to :user
end
@user.comments(:all).map {|c| ...do my calculations here...}
or is there some better way?
或者有更好的方法吗?
thanks! Oren
谢谢!奥伦
采纳答案by teich
In this case, the best solution for me was to either do it in straight SQL, or to use the Ruby group_by function:
在这种情况下,对我来说最好的解决方案是直接用 SQL 来完成,或者使用 Ruby group_by 函数:
@user.all.group_by{ |u| u.created_at.beginning_of_month }
回答by Wojtek Kruszewski
In Postgres you can do:
在 Postgres 中,您可以执行以下操作:
@user.comments.group("DATE_TRUNC('month', created_at)").count
to get:
要得到:
{"2012-08-01 00:00:00"=>152, "2012-07-01 00:00:00"=>57, "2012-09-01 00:00:00"=>132}
It accepts values from "microseconds" to "millennium" for grouping: http://www.postgresql.org/docs/8.1/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC
它接受从“微秒”到“千年”的值进行分组:http: //www.postgresql.org/docs/8.1/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC
回答by Ahmad Hussain
Here is the more refined version of this
这是更精致的版本
@user.comments.group("year(created_at)").group("month(created_at)").count
回答by Mike Tunnicliffe
My guess would be something like:
我的猜测是这样的:
@user.comments.count(:group => "year(created_at),month(created_at)")
Dry-code, ymmv
干码,ymmv
回答by Austio
Use group_by
使用 group_by
@user.comments.group_by(&:week)
class User < ActiveRecord::Base
def week
some_attribute_like_date.strftime('%Y-%W')
end
end
This will give you a grouped list in the format of YYYY-WW
这将为您提供 YYYY-WW 格式的分组列表
回答by Pavan Katepalli
Check out the group date gem
查看组约会宝石
https://github.com/ankane/groupdate
https://github.com/ankane/groupdate
it has recent commits, works with postgresql, integrates easily with chart kick for fast charting, and works with time zones!!
它有最近的提交,可与 postgresql 一起使用,可轻松与 chart kick 集成以实现快速制图,并适用于时区!!
回答by Jim Gilliam
Check out the has_activity plugin.
查看 has_activity 插件。

