I think, You can use the from()
method from the Active Record interface. You can use a subquery as a table for a SQL select statement with help of from()
method. check the below example. In this way, you will get the active record object.
subquery = Setting.limit(10)
Setting.from("(#{subquery.to_sql}) settings")
In your case,
subquery = "(SELECT cars.*,
manufacturer.company_name AS manufacturer_company_name,
services.a_num AS service_a_num,
(SELECT car_documents.file_url FROM car_documents
WHERE car_documents.car_id = cars.id AND car_documents.doc_type = 1 LIMIT 1) AS doc1_file_url,
(SELECT car_documents.file_s3_url FROM car_documents
WHERE car_documents.cart_id = cars.id AND car_documents.doc_type = 3 LIMIT 1) AS file_inv,
(SELECT car_data.demand_lvl FROM car_data
WHERE car_data.car_id = cars.id) AS demand_lvl,
(SELECT car_logs.invoice FROM car_logs
WHERE car_logs.car_id = cars.id AND car_logs.invoice = 1 LIMIT 1) AS invoice_sent
FROM "cars"
INNER JOIN "services" ON "services"."id" = "cars"."service_id"
LEFT JOIN manufacturers ON manufacturers.id = cars.manufacturer_id
WHERE (cars.status_id != 6
AND cars.delivery_date < NOW() - INTERVAL '15 days'
) ORDER BY cars.pickup_date ASC)"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…