2

How would I use Rails ActiveRecord to write a query similar to this?

select
    table1.category as "Collection",
    count(table4.category) as "Totals"
from
    table1 
group by table1.name
order by "Totals" desc

The goal here is to simply report on the number of categories in the table. I've tried a few permutations of .select() and .count(), but my newbness is too great. =/

Maybe it will help if I provide an expected results set. Something like:

| Collection | Totals |
| ---------- | ------ |
| category1  |     10 |
| category5  |      9 |
| category8  |      5 |
| category3  |      3 |
jktravis
  • 1,427
  • 4
  • 20
  • 36

1 Answers1

1
Collection.pluck(:category).inject(Hash.new(0)) { |h, e| h[e] += 1 ; h }
Brad Werth
  • 17,411
  • 10
  • 63
  • 88
  • Interesting. So, it seems there is no AR equiv, eh? Just so I understand, you're taking all the records from the query and putting them in a new Hash, while iterating over each record, and adding to the Hash value? – jktravis Sep 05 '14 at 15:46
  • You're exactly right. The query just returns an array of all of the categories, so at least you're not making a pile of Collections. I can't think of a way to do it in AR better (or at all, off the too of my head)... – Brad Werth Sep 05 '14 at 15:59