ruby 如何在Rails中编写“distinct on”查找器方法?

p4tfgftt  于 2023-06-22  发布在  Ruby
关注(0)|答案(1)|浏览(102)

我使用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)

但我发现它的作用不同。

bnl4lu3b

bnl4lu3b1#

Postgres DISTINCT ON语句没有Rails内置方法。您可以在select中使用DISTINCT ON

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

这将生成与您的示例中完全相同的查询。

相关问题