I have 3 models: Post
, Comment
, User
我有三个模型:Post, Comment, User
Post
has many Comments
文章有很多评论
Comment
belongs to User
属于用户评论
User
has field country_code
用户现场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.
我需要的是一个类似的结果,其中国家代码是键,而值是注释数组。我不知道该怎么做。
3 个解决方案
#1
4
You could use the group_by that comes with the Ruby enumeration module
您可以使用Ruby枚举模块附带的group_by
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.
我想要得到相反方向的排序你可以用排序块的长度乘以-1。
post.comments.group_by{ |c| c.user.country_code }.sort_by{ |k, v| v.length * -1 }
#2
1
Try something like this: (Un-tested):
试一下:
post.comments.joins(:users).select("users.country_code, count(1) as count_all").group("users.country_code").order('count_all desc')
#3
-2
I think if you use group by the grouping will occur in sql returning an aggregate result which won't have all of the comments. You should include user and then group in ruby. Something like this:
我认为,如果您使用group by分组,那么sql将返回一个没有所有注释的聚合结果。您应该在ruby中包含用户和组。是这样的:
post.comments.includes(:users).inject({}){|r, x| r[x.user.country_code].nil? ? r[x.user.country_code] = [x] : r[x.user.country_code] << x;r}
#1
4
You could use the group_by that comes with the Ruby enumeration module
您可以使用Ruby枚举模块附带的group_by
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.
我想要得到相反方向的排序你可以用排序块的长度乘以-1。
post.comments.group_by{ |c| c.user.country_code }.sort_by{ |k, v| v.length * -1 }
#2
1
Try something like this: (Un-tested):
试一下:
post.comments.joins(:users).select("users.country_code, count(1) as count_all").group("users.country_code").order('count_all desc')
#3
-2
I think if you use group by the grouping will occur in sql returning an aggregate result which won't have all of the comments. You should include user and then group in ruby. Something like this:
我认为,如果您使用group by分组,那么sql将返回一个没有所有注释的聚合结果。您应该在ruby中包含用户和组。是这样的:
post.comments.includes(:users).inject({}){|r, x| r[x.user.country_code].nil? ? r[x.user.country_code] = [x] : r[x.user.country_code] << x;r}