2017-06-13 45 views
0

如何創建一個ActiveRecord查詢以下SQL查詢如何創建的ActiveRecord以下SQL

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

回答

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) 
)