This is an age-old question where given a table with attributes \'type\', \'variety\' and \'price\', that you fetch the record with the minimum price for each type there is.
I've been fighting with this for a while and for the moment it seems that you are pretty much stuck with generating SQL.
However, I have a couple refinements to offer.
Instead of find_by_sql
, as @François suggested, I've used ActiveRecord's to_sql
and joins
to "guide" my SQL a little bit:
subquery_sql = Table.select(["MIN(price) as price", :type]).group(:type).to_sql
joins_sql = "INNER JOIN (#{subquery_sql}) as S
ON table.type = S.type
AND table.price = S.price"
Table.joins(joins_sql).where().order()
As you can see, I'm still using raw SQL, but at least it's only on the part where AR gives no support (AFAIK ActiveRecord simply can't manage INNER JOIN ... ON ...
) and not on the whole thing.
Using joins
instead of find_by_sql makes the query chainable - you can add extra conditions, or sort the table, or put everything in a scope.