Dav*_*ave 2 postgresql finder ruby-on-rails distinct ruby-on-rails-5
我将 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;
Run Code Online (Sandbox Code Playgroud)
我的模型名称是 CryptoPrice,但我不清楚如何将上述转换为 finder 方法。这个
CryptoPrice.distinct.pluck(:crypto_currency_id)
Run Code Online (Sandbox Code Playgroud)
不做同样的事情,正如我发现的那样。
PostgresDISTINCT ON语句没有 Rails 内置方法。似乎您可以DISTINCT ON在选择中使用:
CryptoPrice.select('DISTINCT ON (crypto_currency_id) *')
.order(:crypto_currency_id, last_updated: :desc)
Run Code Online (Sandbox Code Playgroud)
这将产生与您的实例完全相同的查询。
| 归档时间: |
|
| 查看次数: |
1696 次 |
| 最近记录: |