使用活动记录查询的原始SQL查询和查询写入会得到不同的结果

时间:2015-07-24 15:37:16

标签: sql ruby-on-rails postgresql

我正在运行两个查询,在第一次运行原始sql查询时:

SELECT  drivers.*, shift_timing.* FROM "drivers" 
        LEFT JOIN(SELECT DISTINCT ON (driver_id) driver_id, 
        start_hour, start_minutes, end_hour, end_minutes FROM 
        shift_timings ORDER BY driver_id) AS shift_timing ON 
        drivers.id = shift_timing.driver_id WHERE 
        "drivers"."deleted_at" IS NULL  ORDER BY "drivers"."id" ASC LIMIT 1

给出了以下输出:

{"id"=>"1", "driver_name"=>"Narendra Kumar Soni", ...,
 "last_order_id"=>"31550", "last_shift_id"=>"74483", "driver_id"=>"1", 
 "start_hour"=>"7", "start_minutes"=>"0", "end_hour"=>"19", 
 "end_minutes"=>"0"}

但是当我运行以下查询时,它完全转换为原始sql查询:

Driver.joins('LEFT JOIN(SELECT DISTINCT ON (driver_id) driver_id, 
              start_hour, start_minutes, end_hour, end_minutes FROM 
              shift_timings ORDER BY driver_id) 
              AS shift_timing ON drivers.id = 
              shift_timing.driver_id')
             .select('drivers.*, shift_timing.*').first    

我得到以下结果:

#<Driver id: 1, driver_name: "Narendra Kumar Soni", ...,
, last_order_id: 31550, last_shift_id: 74483>

基本上,活动记录查询结果中缺少start_hour,start_minutes,end_hour,end_minutes列,缺少的列实际上是班次计时表的列。有人可以解释为什么会发生这种情况以及如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

通常可以使用['name']语法访问联接表中的Fiels,因此它看起来像driver['start_hour']

但我认为解决问题的正确方法是包括shift_timings表格,如

Driver.includes(:shift_timings)

答案 1 :(得分:1)

删除select子句以获取完整的ActiveRecord对象并改为使用includes(:shift_timings),或使用pluck仅获取所需的字段作为数组:

Driver.joins('LEFT JOIN ...') # As in the question
      .pluck('drivers.driver_name, shift_timings.start_hour, shift_timings.start_minutes')