DonMB
DonMB

Reputation: 2718

How can I count unique values in a table in Rails?

I have a table "stock" which consists of many package_ids

package_id = 1  
package_id = 3  
package_id = 2  
package_id = 3  
package_id = 3  
package_id = 4  
package_id = 2

What is the most elegant way to:

I have tried this step by step:

This however does not seems to be an effective path though.

Upvotes: 3

Views: 2143

Answers (2)

cristian
cristian

Reputation: 8744

How about:

Stock.group(:package_id).count

It will return a hash having package_id as a key and the count as a value:

{ package_id1: count1, package_id2: count2 ....}

Upvotes: 6

Baldrick
Baldrick

Reputation: 24340

Try with this to get the 'Top 3':

Stock.select('package_id, count(*) as c').group(:package_id).order('c DESC').limit(3)

Upvotes: 5

Related Questions