Grouping by week/month/etc & ActiveRecord?

前端 未结 7 1285
野的像风
野的像风 2020-12-01 09:22

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

相关标签:
7条回答
  • 2020-12-01 09:24

    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

    0 讨论(0)
  • 2020-12-01 09:27

    My guess would be something like:

    @user.comments.count(:group => "year(created_at),month(created_at)")
    

    Dry-code, ymmv

    0 讨论(0)
  • 2020-12-01 09:34

    Here is the more refined version of this

    @user.comments.group("year(created_at)").group("month(created_at)").count
    
    0 讨论(0)
  • 2020-12-01 09:34

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

    0 讨论(0)
  • 2020-12-01 09:36

    Check out the has_activity plugin.

    0 讨论(0)
  • 2020-12-01 09:37

    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 }
    
    0 讨论(0)
提交回复
热议问题