Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all records grouped by field from association and sorted by count in group

I have 3 models: Post, Comment, User

Post has many Comments

Comment belongs to User

User has field country_code

I want to get all post comments grouped by country code AND sorted by amount of comments per country.

This query:

post.comments.joins(:user).group("users.country_code").order('count_all desc').count

returns such kind of result:

{"DE"=>67,
"US"=>8,
"RS"=>8,
"IN"=>8,
"ES"=>7,
"BR"=>6,
...
"UA"=>0

}

What I need is a similar result where country codes are keys but values are arrays of comments. I don't know how to achieve this.

like image 723
Shkarik Avatar asked Aug 27 '15 16:08

Shkarik


1 Answers

You could use the group_by that comes with the Ruby enumeration module

post.comments.group_by{ |c| c.user.country_code }

If you also want it ordered by amount of comments in each group that's also possible:

post.comments.group_by{ |c| c.user.country_code }.sort_by{ |k, v| v.length }

I suppose to get the sorting in the opposite direction you could multiply the length by -1 in the sort block.

post.comments.group_by{ |c| c.user.country_code }.sort_by{ |k, v| v.length * -1 }
like image 154
Toby 1 Kenobi Avatar answered Sep 19 '22 10:09

Toby 1 Kenobi