Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by ruby on rails

I need to group the users based on created_at column by year and month,

User.all.group_by{ |q| [q.created_at.year, q.created_at.month]}, where I am getting hash with key [year, month], Is there any way to group the records which results like

{ 
  year1 =>{ month1 =>[array of records], month2=>[array]}, 
  year2 =>{ month1 =>[array of records], month2=>[array]}
}
like image 600
Aarthi Avatar asked Nov 18 '25 20:11

Aarthi


2 Answers

Try to the following:

User.all
  .group_by { |user| user.created_at.year }
  .transform_values { |users| users.group_by { |user| user.created_at.month } }
like image 140
fongfan999 Avatar answered Nov 21 '25 13:11

fongfan999


you can get by

result = {}
User.all.each do |user|
   result[user.created_at.year] = {} if !result[user.created_at.year].present?
   result[user.created_at.year][user.create_at.month] = []  if !result[user.created_at.year][user.create_at.month].present?
   result[user.created_at.year][user.create_at.month].push(user.attributes)
end
like image 45
NRaghavendra Avatar answered Nov 21 '25 12:11

NRaghavendra