如何为以下Sql查询创建ActiveRecord查询
SELECT device1.*
FROM devices device1
WHERE device1.id = (SELECT MAX(device2.id)
FROM devices device2
WHERE device2.user_id = device1.user_id);
我的Device
模型带有user_id
列
我不希望用户find_by_sql
,因为它会返回Array
而不是ActiveRecord Array
答案 0 :(得分:2)
我认为:
Device.where(id: Device.select("MAX(id)").from('devices devices2').where("devices2.user_id = devices.user_id"))
将产生:
SELECT "devices".*
FROM "devices"
WHERE "devices"."id" IN (
SELECT MAX(id)
FROM devices devices2
WHERE (devices2.user_id = devices.user_id)
)