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.
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 }
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