Group records by both month and year in Rails

后端 未结 5 1243
走了就别回头了
走了就别回头了 2021-02-07 09:28

I\'m on Ruby 1.9.2, Rails 3.0.x and I use MySQL DB. I have a Messages Model, where one can post new messages every day.

I have an index action where I want to display t

相关标签:
5条回答
  • 2021-02-07 09:35

    In SQL:

    select * from messages group by year(created_at), month(created_at);
    

    In Rails:

    Message.all.group_by { |m| m.created_at.beginning_of_month }
    
    0 讨论(0)
  • 2021-02-07 09:51

    Use Group Date.

    It supports time zones, so if you ever need to - the code will easily evolve.

    https://github.com/ankane/groupdate

    0 讨论(0)
  • 2021-02-07 09:52
    ModelName.all.group_by { |m| m.created_at.month }
    

    This will work, however month will be returned as the index. Ex. Nov would refer to 11

    0 讨论(0)
  • 2021-02-07 09:58
    Message.select("date_trunc('month', created_at) as month").group("month")
    
    0 讨论(0)
  • 2021-02-07 09:58

    To group by year and by month (e.g. not having december 2020 with december 2021):

    Message.group("date_trunc('year', created_at), date_trunc('month', created_at)")
    

    Tested on PostgreSQL

    0 讨论(0)
提交回复
热议问题