且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rails / ActiveRecord按月和年分组并计数

更新时间:2023-01-29 21:51:30

我假设您的表按照Rails约定是单个相册

I'm assuming your table is singular Album per Rails convention. If not, consider changing it.

 Album.all.map { |album| [Date::MONTHNAMES[album.date.month], album.date.year].join(' ') }
  .each_with_object(Hash.new(0)) { |month_year, counts| counts[month_year] += 1 }

说明:

.map 方法遍历相册并返回由 [ month year, month year, ...]

The .map method iterates over the albums and returns an array of strings consisting of ["month year", "month year", ... ].

.each_with_object 方法是一种标准计数算法,可为每个唯一数组项返回带有计数的哈希。

The .each_with_object method is a standard counting algorithm that returns a hash with a count for each unique array item.