Is it me, or does the ActiveQuery Rails Guide example for using group (link) not make sense?
To apply a GROUP BY clause to the SQL fired by the finder, you can specify the group method on the find.
For example, if you want to find a collection of the dates orders were created on:
Order.select("date(created_at) as ordered_date, sum(price) as total_price").group("date(created_at)")
And this will give you a single Order object for each date where there are orders in the database.
The SQL that would be executed would be something like this:
SELECT date(created_at) as ordered_date, sum(price) as total_price FROM orders GROUP BY date(created_at)
This just gets an ActiveRecord::Relation collection of objects with a single id attribute set to nil. What they’re saying they really want, “a collection of dates that the orders were created on,” would be easily achieved via Order.select('date(created_at)').distinct.
I’m starting to get paranoid about documentation after my troubles with Rails 4.x’s completely incorrect enum documentation (Justin I saw your blog post on it only a week after I had my own hair-tearingly frustrating episode with it).
Negative, I actually created a test project from scratch to figure this out. All this does is return an ActiveRecord collection of Order objects, except they only have a single attribute id, and it’s set to nil. That was my point—this can’t be the intended behavior because it’s so useless.
The Rails bug/report contributing process just seems too complex to bother with in my opinion. I saw the one you wrote for the enum functionality and despite the doc being completely wrong and it not functioning as intended, they just said “yeah it’s broken we’ll fix it in Rails 5” and left the documentation like that.