Say we want to filter a table matching pairs of values. E.g. For each account we want to select all items from the most recent transaction. First we group most recent transactions by account id, then we filter all items the associated transaction has by processed_at
and account_id
in the array of pairs we retrieved in the first query.
tuples = Transaction.where.group(:acount_id).pluck('account_id, max(processed_at)')
Item.joins(:transaction).where("(transactions.account_id, transactions.processed_at) IN (VALUES #{tuples.map { '(? ,?)' }.join(' ,')})", *tuples.flatten)
Conveniently we can use SQLs VALUES Show archive.org snapshot function to wrap any values in a set of rows:
Posted by Jan Bussieck to 9elements's deck (2020-11-14 10:52)