在Rails中按月和年分组记录 [英] Group records by both month and year in Rails

查看:207
本文介绍了在Rails中按月和年分组记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Ruby 1.9.2上,Rails 3.0.x和我使用MySQL DB。我有一个消息模型,每天可以发布新消息。



我有一个索引动作,我想要显示按月份和年份分组的这些消息。这基本上用于过滤邮件。



我的查询看起来像这样: - $ / $>

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

在引用之后,我在Rails中使用了group_by函数这个帖子



My Group By Query是: -

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

我返回了一个名为@msgs_by_month的Hash。这有助于我按月分组消息,但我需要考虑年份,形成一个独特的密钥,因为这有助于区分2011年9月和2012年9月之间的消息。 p>

我当前的键只是类型Hash [Month](例如9月份的Hash [9] =>,我可以显示所有适当的值)。我怎样才能得到一个类型月,年的独特的钥匙,我可以很容易地循环显示按月份和年份创建的所有记录。



谢谢

>

编辑: -



我想要做到这一点的一种方法,使用这里提供的 created_at.to_date api
。我只是想知道,我如何能从 created_at.to_date 中删除​​当天以获得唯一月份和年份组合键,它可以与group_by函数一起使用

解决方案

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

在Rails中:

  Message.all.group_by {| m | m.created_at.beginning_of_month} 


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.

解决方案

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 }

这篇关于在Rails中按月和年分组记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆