Ruby on rails 将复杂SQL联接转换为Rails ActiveRecord查询
我有下面的SQL,它在PGAdmin中正确执行,但是尽管我尝试,我无法使连接正常工作和执行Ruby on rails 将复杂SQL联接转换为Rails ActiveRecord查询,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我有下面的SQL,它在PGAdmin中正确执行,但是尽管我尝试,我无法使连接正常工作和执行 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" = "So
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查询。我有两个具体的问题,试图
包括(阅读:{sources::location\u mappings})
以及如何正确设置“where”方法的格式。任何帮助都将不胜感激
“Reading\u ID”、“Pixel\u ID”、“Level”
是PixelReadings模式中的所有列-我需要所有PixelReading列加上Readings表中的Time列。在rails模型上是否正确设置了表名?我发现表名与rails约定不一致。如果尚未设置它们,可以这样设置它们(对于表名与rails约定不同的所有模型,也可以这样做):
读数
应该在包含中,因为他需要访问它,不是吗?可能是,我不完全确定。根据我的记忆,连接
和包含
不需要一起使用,但我可能错了。想知道@Ash是否可以尝试并让我们知道。joins不会提供该记录。一旦我进行了pixel\u读取。读取
Rails将再次加载读取。如果包含,则这些记录可用。我也不能说Rails将如何处理它们,将它们粘在一起,但我确信使用连接
时,如果没有第二次查询,它们将不可用。这是正确的,如果我们需要快速加载,包含
。但是,如果我们只是在查询中引用表,我们就不需要includes
我猜。是的,我们不需要<代码>连接
将帮助我们通过关联搜索,但不会加载它们。
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)