I have three models Field
, Flight
, and FieldBoundaryDetail
. Field
has many Flights
and has one FieldBoundaryDetail
Basically, i want to get every Field
and FieldBoundaryDetail
with the last flight.
I have written it in SQL. For sorting and searching purposes, i need it to be a Rails ActiveRecordRelation but am having a hard time converting this to Rails.
SELECT *
FROM fields
LEFT JOIN (SELECT *
FROM (SELECT *
FROM flights
ORDER BY event_date DESC) AS flight
GROUP BY flight.field_id
) AS flight ON fields.id = flight.field_id
INNER JOIN field_boundary_details ON fields.id = field_boundary_details.field_id
As a simple answer, you can use find_by_sql
with the query you have, slightly modified:
Fields.find_by_sql "SELECT fields.*
FROM fields
LEFT JOIN (SELECT *
FROM (SELECT *
FROM flights
ORDER BY event_date DESC) AS flight
GROUP BY flight.field_id
) AS flight ON fields.id = flight.field_id
INNER JOIN field_boundary_details ON fields.id = field_boundary_details.field_id"
I have a solution, but it's not very elegant. Hopefully someone can give a better answer.
latest_flight_ids = Field.latest_flight_for_each_field.map {|flight| flight.id.to_s}.join(",")
Field.select("*").
joins("LEFT JOIN flights on fields.id = flights.field_id").
joins(:field_boundary_detail).
where("flights.id IN(#{latest_flight_ids}) OR flights.id IS NULL")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.