ActiveRecord joins on aggregate query

余生长醉 提交于 2019-12-11 08:56:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!