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 comment
In Postgres you can do:
@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
My guess would be something like:
@user.comments.count(:group => "year(created_at),month(created_at)")
Dry-code, ymmv
Here is the more refined version of this
@user.comments.group("year(created_at)").group("month(created_at)").count
Check out the group date gem
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!!
Check out the has_activity plugin.
In this case, the best solution for me was to either do it in straight SQL, or to use the Ruby group_by function:
@user.all.group_by{ |u| u.created_at.beginning_of_month }