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

activerecord, ruby-on-rails

Solution

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

Problem

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: - count each unique package_id in the db, e.g.: package_id 1 = one time in the db; package_id 2 = two times in the db; package_id 3 = three times in the DB ... - echo the top 3 of package IDs afterwards I have tried this step by step: - counting each single package_id (Stock.where(:package_id => 1).count) - putting that all in an array - and sort that array from high to low (only first 3 items) This however does not seems to be an effective path though.

Original source