问题
I have a Unit model that has_many :transacions. Transaction has a type column that indicates what kind fo transaction it is: sale, transfer, reservation, etc.
I would like to find all units that have a given transaction type as their latest transaction. I can't figure out how to do it in ActiveRecord.
In SQL, if for example I wanted to find all units with "Transfer" as their latest transaction I could do:
SELECT u.*, tx.* FROM units u INNER JOIN transactions tx ON u.id=tx.unit_id
INNER JOIN
(
SELECT tx.unit_id, max(tx.created_at) AS latest_tx_date
FROM transactions tx
GROUP BY tx.unit_id
ORDER BY tx.unit_id
) max_dates
ON (tx.unit_id=max_dates.unit_id AND tx.created_at>=max_dates.latest_tx_date)
WHERE tx.type='Transfer';
It's the joining with the inner query that I'm having trouble with. Is there a readable ActiveRecord way to do this or should I just use the SQL?
回答1:
ActiveRecord supports single table inheritance. No need to write plain SQL.
来源:https://stackoverflow.com/questions/19709552/activerecord-joins-on-aggregate-query