Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a "distinct on" finder method in Rails?

I'm using RoR 5.0.1 with PostGres 9.5. I have the following query that gets distinct records from a specific table (represented by a corresponding model) based on a date

select distinct on (crypto_currency_id) t.* 
from crypto_prices t 
order by crypto_currency_id, last_updated desc;

My model name is CryptoPrice, but I'm unclear how to convert the above into a finder method. This

CryptoPrice.distinct.pluck(:crypto_currency_id)

doesn't do the same thing, as I discovered.

like image 490
Dave Avatar asked Jan 25 '26 09:01

Dave


1 Answers

There isn't Rails built-in method for Postgres DISTINCT ON statement. It seems like you could use DISTINCT ON in your select:

CryptoPrice.select('DISTINCT ON (crypto_currency_id) *')
           .order(:crypto_currency_id, last_updated: :desc)

This will produce exactly the same query as in your instance.

like image 118
Ilya Avatar answered Jan 27 '26 01:01

Ilya