Trying to retrieve an array of ActiveRecord Objects grouped by date with PostgreSQL.
More specifically I\'m trying to translate the following MySQL query:
The PostgreSQL feature you want to use here is DISTINCT ON. There are two basic ways to go about making this query via ActiveRecord.
The first method is to just specify the :select and :order options. This works great when you have a fairly simple query with no :joins or :include.
Post.all(
:select => 'DISTINCT ON (date::date) *',
:order => 'date::date DESC, created_at DESC'
)
If you have a more complex query where ActiveRecord generates its own SELECT clause, you can use a subquery to select the target records.
Post.all(
:joins => 'INNER JOIN (SELECT DISTINCT ON (date::date) id FROM posts ORDER BY date::date DESC, created_at DESC) x ON x.id = posts.id'
)
Note that this could be a fair bit slower than the first method depending on your data. I would only use this method if required. Be sure to benchmark with production-like data.