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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With