ruby on rails - Group by month+year with counts -


i have table of albums has date column named release_date.

i want list of month + year combinations present along number of albums released in month/year.

so, output might like:

  • november 2016 - 11
  • october 2016 - 4
  • july 2016 - 19
  • december 2015 - 2

ruby 2.3.1 w/ rails 5 on postgres 9.6, fwiw.

i'm assuming table 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 } 

explanation:

the .map method iterates on albums , returns array of strings consisting of ["month year", "month year", ... ].

the .each_with_object method standard counting algorithm returns hash count each unique array item.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -