将复杂SQL连接转换为Rails ActiveRecord查询

时间:2016-07-26 07:38:52

标签: ruby-on-rails activerecord

我有以下在PGAdmin中正确执行的SQL,但尽可能尝试,我无法使连接正常工作并正确执行。

SELECT "Reading_ID", "Pixel_ID", "Level", "Readings"."Time"
  FROM "PixelReadings"
    INNER JOIN "Readings" ON ("Reading_ID" = "Readings"."ID")
      INNER JOIN "Sources" ON ("Readings"."Source_ID" = "Sources"."ID")
        INNER JOIN location_mappings ON ("Sources"."ID" = "location_mappings"."source_id")
  WHERE ("Readings"."Time" BETWEEN '2016-07-25 06:03:07 UTC' AND '2016-07-26 06:03:07 UTC')
    AND "location_mappings"."location_id" = 16
    AND ("location_mappings"."use_order" = 0)
    AND "Pixel_ID" = ("location_mappings"."pixel_y" * 511) + "location_mappings"."pixel_x"
  ORDER BY ("Reading_ID") ASC
LIMIT 4;

任何人都可以帮助将其转换为ActiveRecord查询。我有2个具体问题,试图获得

.includes(readings: {sources: :location_mappings})

以及如何正确格式化'where'方法。任何帮助将不胜感激。

"Reading_ID", "Pixel_ID", "Level"是PixelReadings架构中的所有列 - 我需要所有PixelReading列以及Readings表中的Time列。

1 个答案:

答案 0 :(得分:1)

是否在您的导轨型号上正确设置了表名?我看到表名与rails约定不一致。如果您还没有设置它们,您可以像这样设置em(对于没有表名与rails约定不同的所有模型也一样):

class PixelReading < ActiveRecord::Base
 self.table_name = "PixelReadings"
end

您的查询看起来像这样

PrixelReading
 .joins(readings: {sources: :location_mappings})
 .where("Readings.Time BETWEEN '2016-07-25 06:03:07 UTC' AND '2016-07-26 06:03:07 UTC'")
 .where(location_mappings: { location_id: 16, use_order: 0 })
 .where("Pixel_ID = (location_mappings.pixel_y * 511) + location_mappings.pixel_x")
 .order("PixelReadings.Reading_ID ASC")
 .select("PixelReadings.*, Readings.Time")
 .limit(4)