rails 按 created_at 的日期分组记录 [英] rails group records by dates of created_at

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

问题描述

所以我有一个模型,我想检索记录并按 created_at 字段的日期对它们进行分组.但是 created_at 是一个日期时间字段,我只对日期部分感兴趣.所以我正在寻找类似二维数组的东西,第一层是以日期字符串为键的散列,第二层将是带有记录的数组.我该怎么做?

<前>{"9/28/2012" => [记录,记录,记录],"9/29/2012" => [记录,记录,记录],"9/30/2012" => [记录,记录,记录]}

以上,如果我想将上述安排应用于从此模型中检索到的所有记录,我该怎么做?

解决方案

ActiveRecord group 方法将满足您的需求.在您的情况下,问题在于使用 created_at 这是一个日期时间,以及您按日期分组的约束.由于将日期时间转换为日期是特定于数据库的,因此代码也需要特定于数据库.

对于 MySql,你可以这样做:

Model.group("date(table_name.created_at)")

对于 SQLite,您可以:

Model.group("strftime('%Y-%m-%d', table_name.created_at)")

对于 PostgreSQL:

Model.group("table_name.created_at::date")

不幸的是,此代码不可移植,但这对您来说可能无关紧要.如果是这样,您始终可以构建一个包装方法,根据您的 DBMS 选择正确的转换语法.

So I have a model that I want to retrieve records and group them by dates of the created_at field. But created_at is a datetime field, and I am only interested in the date part. So I am looking for something like a 2D array, first layer would a hash with date string as the key, second layer would be arrays with records. How should I do it?

{
"9/28/2012" => [record, record, record],
"9/29/2012" => [record, record, record],
"9/30/2012" => [record, record, record]
}

At top of the above, how should I do it if I want the above arrange be applied to all records retrieved from this model?

解决方案

ActiveRecord group method will do what you need. In your case, the problem will be with using created_at which is a datetime, and your constraint to group by date. Since casting date-times to dates is database-specific, the code will need to be database-specific as well.

For MySql you can do:

Model.group("date(table_name.created_at)")

For SQLite you can do:

Model.group("strftime('%Y-%m-%d', table_name.created_at)")

And for PostgreSQL:

Model.group("table_name.created_at::date")

This code will unfortunately not be portable, but that may not matter to you. If it does, you can always build a wrapper method that selects the correct conversion syntax based on your DBMS.

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

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