Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails count values returned from pluck

I am building a rails application, and I need to create some charts.

I am running this query to retrieve the answers from the user:

quiz = Quiz.select("answer1").where(completed: true).pluck(:answer1)

And the query returns for me this: [1, 2, 1, 1, 1]

I want to count the values and group them like this: { 1 => 4, 2 => 1 }

I have tried to use group by and count but it is not working, I could do this manually but I wanted to use just SQL to achieve this.

I remember to use group by and count using sql, but I am not sure how to do this using rails.

like image 704
Gabriel Mesquita Avatar asked Dec 18 '22 03:12

Gabriel Mesquita


1 Answers

You can group('answer1') as described here

Quiz.where(completed: true).group('answer1').count

Hope it helped!

like image 98
Rodrigo Chaves Avatar answered Dec 28 '22 19:12

Rodrigo Chaves