A vehicle has_many services. services has_many types (0,1,2,3,4).
I need to write a query that shows the mileage reading of when each type of service was last completed for a vehicle.
In my MS ACCESS days this was a simple crosstab (transform) query. Could someone point me in the right direction in the rails environment? Thanks
This is the long hand version of what I'm trying to collate:
@a_last = v.services.maximum(:mileage_closed, :conditions => ["closed = TRUE AND service_type_id > 0"])
@b_last = v.services.maximum(:mileage_closed, :conditions => ["closed = TRUE AND service_type_id > 1"])
@c_last = v.services.maximum(:mileage_closed, :conditions => ["closed = TRUE AND service_type_id > 2"])
@d_last = v.services.maximum(:mileage_closed, :conditions => ["closed = TRUE AND service_type_id > 3"])
@e_last = v.services.maximum(:mileage_closed, :conditions => ["closed = TRUE AND service_type_id > 4"])
Thanks!
The simple answer is to iterate through a range and collect your results:
mileages = (0..4).collect do |service_type|
vehicle.services.maximum(:mileage_closed, :conditions => ["CLOSED = TRUE AND SERVICE_TYPE_ID = #{service_type}"]
end
I'm guessing you mean to search the service type id with an equals instead of a more than.
This will, however, make 5 sql statements when it is run. You'll probably find this doesn't effect performance too badly. If performance does become an issue, a different approach would be to write an SQL statement to find your results (it'll be grouped by vehicle_id and service_type_id, then run a MAX() on the mileage_closed column) and make that a view in your database. Then you should be able to find these results in a single database round trip.
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.