Group records by both month and year in Rails

∥☆過路亽.° 提交于 2019-12-21 03:39:18

问题


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 these messages grouped by both month and year. This basically is used to filter messages.

My query looks like this:-

@active_msgs = Messages.where('expiry > ?', Time.now).order('created_at DESC')

I used the group_by function in Rails, after referring to this post

My Group By Query is:-

@msgs_by_month = @active_msgs.all.group_by {|u| u.created_at.month }

I was returned a Hash called @msgs_by_month. This helped me group the messages by month, but I need to taken into account the year, to form a unique key , as it would help me differentiate between for e.g., Sept 2011 and Sept 2012.

My current key only is of type Hash[Month] ( e.g. Hash[9] => for month of September, I can display all appropriate values ). How can i get a unique key of type month, year which I can easily loop though to display all records grouped by Month and Year of creation.

Thank you

EDIT:-

I'm guessing one way to do this, is to make use the created_at.to_date api, provided here . I only wonder, how I can strip out the day from created_at.to_date to get a unique month and year combination key which could work with the group_by function.


回答1:


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 }



回答2:


Use Group Date.

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

https://github.com/ankane/groupdate




回答3:


Message.select("date_trunc('month', created_at) as month").group("month")



回答4:


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



来源:https://stackoverflow.com/questions/12526161/group-records-by-both-month-and-year-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!