如何获取 rails 中每个月创建的记录
How to get records created in each month in rails
正在寻找一种方法来获取每个月为 table
创建的所有记录
例如,我需要知道如何获得如下结果:
January: 6,
Feb: 9,
March: 10
理想情况下,我正在考虑使用数据库中的 created_at
字段进行比较。
假设您有一个用户 table(我的 Rails 应用程序有一个),如下所示:
id
name
.
.
.
created_at
updated_at
您可以使用此代码,它将 return 月份的哈希值与计数:
users = User.all
users.group_by {|u| u.created_at.strftime("%B")}.transform_values {|v| v.count}
Returns 类似于:
{"September"=>33,
"August"=>1,
"October"=>1,
"February"=>55,
"January"=>185,
"May"=>4,
"December"=>145,
"June"=>8,
"November"=>19,
"March"=>51,
"April"=>27,
"July"=>5}
说明
created_at.strftime("%B")
这会将日期转换为月份,使用 strftime
users.group_by {|u| u.created_at.strftime("%B")}
使用 group_by
创建一个按月份名称对用户记录进行分组的散列
.transform_values {|v| v.count}
我们只需要计数,而不是记录集合。我们将 key
单独留在散列中,并使用 transform_values 来计算 values
.
您可以在 SQL 中使用 GROUP BY
和 COUNT
来有效地检索数据。 Rails 在这里提供了各种选项来构建 SQL 查询,该查询使用 ActiveRecord::Calculations
.
执行聚合和计算
假设您有一个名为 Record
的模型用于您的记录,并且您使用 MySQL / MariaDB 作为您的数据库,这可用于获取每月的记录数:
records_per_month = Record.group('EXTRACT(YEAR_MONTH FROM created_at)').count
这将 return 整数散列(对应于组的年份和月份,例如 2022 年 5 月的记录将分组在键 202205
下)和其中的记录数本月作为值。
根据您的示例,这将是
{
202201 => 6,
202202 => 9,
202203 => 10
}
如果需要,您可以进一步“格式化”密钥,例如
records_per_month.transform_keys! do |year_month|
Date.strptime(year_month.to_s, '%Y%m').strftime('%B %Y')
end
在这里,我们将 year-month 整数解析为带有 Date.strptime
and format the date with Date#strftime
的日期以显示月份名称和年份,例如"February 2022"
.
正在寻找一种方法来获取每个月为 table
创建的所有记录例如,我需要知道如何获得如下结果:
January: 6,
Feb: 9,
March: 10
理想情况下,我正在考虑使用数据库中的 created_at
字段进行比较。
假设您有一个用户 table(我的 Rails 应用程序有一个),如下所示:
id
name
.
.
.
created_at
updated_at
您可以使用此代码,它将 return 月份的哈希值与计数:
users = User.all
users.group_by {|u| u.created_at.strftime("%B")}.transform_values {|v| v.count}
Returns 类似于:
{"September"=>33,
"August"=>1,
"October"=>1,
"February"=>55,
"January"=>185,
"May"=>4,
"December"=>145,
"June"=>8,
"November"=>19,
"March"=>51,
"April"=>27,
"July"=>5}
说明
created_at.strftime("%B")
这会将日期转换为月份,使用 strftime
users.group_by {|u| u.created_at.strftime("%B")}
使用 group_by
创建一个按月份名称对用户记录进行分组的散列.transform_values {|v| v.count}
我们只需要计数,而不是记录集合。我们将 key
单独留在散列中,并使用 transform_values 来计算 values
.
您可以在 SQL 中使用 GROUP BY
和 COUNT
来有效地检索数据。 Rails 在这里提供了各种选项来构建 SQL 查询,该查询使用 ActiveRecord::Calculations
.
假设您有一个名为 Record
的模型用于您的记录,并且您使用 MySQL / MariaDB 作为您的数据库,这可用于获取每月的记录数:
records_per_month = Record.group('EXTRACT(YEAR_MONTH FROM created_at)').count
这将 return 整数散列(对应于组的年份和月份,例如 2022 年 5 月的记录将分组在键 202205
下)和其中的记录数本月作为值。
根据您的示例,这将是
{
202201 => 6,
202202 => 9,
202203 => 10
}
如果需要,您可以进一步“格式化”密钥,例如
records_per_month.transform_keys! do |year_month|
Date.strptime(year_month.to_s, '%Y%m').strftime('%B %Y')
end
在这里,我们将 year-month 整数解析为带有 Date.strptime
and format the date with Date#strftime
的日期以显示月份名称和年份,例如"February 2022"
.