Only works with Rails5 due to or request method
specific_ids = CryptoIndexCurrency.distinct.pluck(:crypto_currency_id) hash = CryptoPrice.where(crypto_currency_id: specific_ids) .group(:crypto_currency_id) .maximum(:last_updated) hash.each_with_index do |(k, v), i| if i.zero? res = CryptoPrice.where(crypto_currency_id: k, last_updated: v) else res.or(CryptoPrice.where(crypto_currency_id: k, last_updated: v)) end end
Explanation
You can use group to rearrange your entire CryptoPrice object CryptoPrice each CryptoIndexCurrency in the table.
Then, using maximum (thanks @artgb), you will get the highest last_updated value. This will lead to the output of the Hash using the keys: crypto_currency_id and the value of last_updated .
Finally, you can use keys to get Array crypto_currency_id .
CryptoPrice.group(:crypto_currency_id).maximum(:last_updated) => => {2285=>2017-06-06 09:06:35 UTC, 2284=>2017-05-18 15:51:05 UTC, 2267=>2016-03-22 08:02:53 UTC}
The problem with this solution is that you get the maximum date for each row without getting all records.
To get entries, you can loop the hash in pairs. with crypto_currency_id and last_updated . This is hacking, but the only solution I found.
source share