如何在Rails中编写“distinct on”finder方法?

时间:2017-07-29 22:51:09

标签: ruby-on-rails postgresql ruby-on-rails-5 distinct finder

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

并没有像我发现的那样做。

1 个答案:

答案 0 :(得分:3)

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

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

这将产生与您的实例完全相同的查询。

相关问题