Reputation: 2718
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
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
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