简体   繁体   English

如何在RoR中执行此查询

[英]How to perform this query in RoR

I have a rails active record query which returns a count of the the number of items in each category. 我有一个rails活动记录查询,该查询返回每个类别中项目数的计数。 In the form 形式

Category.joins(:item).group("category_id").count
=> {1=>1, 2=>3}

which gives the correct result. 给出正确的结果。 I'm having an issue including the category name in the result along with item count. 我遇到了一个问题,其中包括结果中的类别名称以及项目数。 How do I include category name eg. 如何包含类别名称,例如。

 1, Severe => 1, 
 2, Minor => 3 

Thanks! 谢谢!

试试这个

Category.joins(:item).group("categories.name").count

You could do: 您可以这样做:

Category.joins(:item).group([:category_id, :category_name]).count

Then you would get something like below: 然后,您将获得以下内容:

{[1, "Severe"]=>1, [2, "Minor"]=>3}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM