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]}
}
Try to the following:
User.all
.group_by { |user| user.created_at.year }
.transform_values { |users| users.group_by { |user| user.created_at.month } }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With