2015-08-27 15 views
2

分组和排序的通过计数的所有记录我有3种型号:PostCommentUser获得由联想场组

Post有许多Comments

Comment属于User

User有场country_code

我想获取所有职位通信按国家代码分组并按每个国家的评论数量排序。

这个查询:

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 

}

我需要的是一个类似的结果,其中国家代码是关键,但值的评论阵列。我不知道如何做到这一点。

回答

0

尝试这样:(未经测试):

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

你可以使用自带的红宝石枚举模块

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

的GROUP_BY如果你也希望它下令量每组中的评论也是可能的:

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

我想如果你使用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} 
+2

如果使用ActiveRecord的方法'group',你说,这将汇总结果,但如果你使用完全不同的Ruby方法'group_by'如图我的回答则它不汇总,并给出所需的结果。不要使用复杂的'inject'模块来做与'group_by'完全相同的事情。 –