Reputation: 5343
I have a table called Sales. And i have a field called plate_number corresponding to a single car.
How can i find the total number of instances of each car in db.
E.g [ [plate_number1, 10 times found], [plate_number2, 5 times found] ]
I tried using
Sale.map(&:plate_number).count
and
Sale.pluck(:plate_number)
but these just do a simple count of that column
any help appreciated
Upvotes: 1
Views: 846
Reputation: 5343
This is a second solution i found for anyone who is interested
Sale.all.group_by { |ss| ss["plate_number"] }.map { |k,v| [k, v.length] }
Upvotes: 0
Reputation: 1951
You need to use count
with group
like:
Sale.group(:plate_number).count
This will return a hash with each plate_number
and the count of occurrences.
# => { 'plate1' => 5, 'plate2' => 2 }
Upvotes: 4