ActiveRecord加入聚合查询

我有一个Unit模型has_many :transacions 。 交易有一个type列,表明它是什么类型的交易:销售,转让,预订等。

我想找到具有给定交易类型的所有单位作为他们的最新交易。 我无法弄清楚如何在ActiveRecord中执行此操作。

在SQL中,如果我想找到所有以“Transfer”作为最新事务的单位,我可以这样做:

 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'; 

这是我遇到麻烦的内部查询的加入。 是否有可读的ActiveRecord方法来执行此操作,还是应该使用SQL?

ActiveRecord支持单表inheritance 。 无需编写纯SQL。