如何为以下sql创建ActiveRecord

时间:2017-06-13 12:18:37

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

如何为以下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

1 个答案:

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