获取按关联字段分组的所有记录,并按组中的计数排序

我有3个型号: PostCommentUser

Post有很多Comments

Comment属于User

User有字段country_code

我想获得按国家/地区代码分组的所有post评论,并按每个国家/地区的评论数量排序。

这个查询:

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

返回这样的结果:

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

}

我需要的是一个类似的结果,其中国家代码是键,但值是注释数组。 我不知道如何实现这一目标。

您可以使用Ruby枚举模块附带的group_by

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

如果您还希望按每个组中的评论数量排序,也可以:

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

我想在相反的方向上进行排序,你可以在排序块中将长度乘以-1

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

尝试这样的事情:(未经测试):

 post.comments.joins(:users).select("users.country_code, count(1) as count_all").group("users.country_code").order('count_all desc') 

我认为如果你使用group by grouping将在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}