MikeW
MikeW

Reputation: 4809

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

Upvotes: 0

Views: 66

Answers (2)

xdazz
xdazz

Reputation: 160843

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}

Upvotes: 3

Igor Drozdov
Igor Drozdov

Reputation: 15045

Try this one

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

Upvotes: 3

Related Questions