将SQL查询转换为ActiveRecord(Rails)

时间:2015-04-20 19:40:26

标签: sql ruby-on-rails activerecord

我在将SQL查询转换为ActiveRecord性能方面遇到了困难。我很感激他们的帮助!

SELECT MAX(distances.max) from 
    (SELECT max(distance) 
        FROM 
            (SELECT * from tracks WHERE car_id=1) t , locations l 
        WHERE t.id=l.track_id 
        GROUP BY track_id) distances;

1 个答案:

答案 0 :(得分:0)

def max_track_length
    sql= Location.select("MAX(distance) as distance")
            .joins("INNER JOIN tracks ON tracks.id=locations.track_id")
            .where("tracks.car_id = ?", self.id).group(:track_id).to_sql
    res=Car.from("(#{sql}) l").maximum("l.distance")
    res||=0;
end