我正在使用RoR 5.0.1和PostGres 9.5。我有以下查询,根据日期
从特定表(由相应的模型表示)中获取不同的记录select distinct on (crypto_currency_id) t.*
from crypto_prices t
order by crypto_currency_id, last_updated desc;
我的模型名称是CryptoPrice,但我不清楚如何将上述内容转换为finder方法。此
CryptoPrice.distinct.pluck(:crypto_currency_id)
并没有像我发现的那样做。
答案 0 :(得分:3)
Postgres DISTINCT ON
语句没有Rails内置方法。您似乎可以在选择中使用DISTINCT ON
:
CryptoPrice.select('DISTINCT ON (crypto_currency_id) *')
.order(:crypto_currency_id, last_updated: :desc)
这将产生与您的实例完全相同的查询。