【发布时间】:2014-08-13 19:02:44
【问题描述】:
我有一个带有以下型号的 Rails4 应用程序:
1. Systems (has many devices, has many parameters through devices)
2. Devices (belongs to a system, has many parameters)
3. Parameters (belongs to a Device)
4. Events (polymorphic - Systems, Devices and Parameters can have events)
创建事件时,会为(事件上的)布尔字段分配一个值。 False 表示失败。
我的事件有一个范围,只显示失败的事件:
scope :failing, -> { where(okay: false).order('created_at desc') }
我可以按如下方式检索事件:
System.events.failing
Device.events.failing
Parameter.events.failing
我正在尝试返回以下系统列表:
1. the most recent event for the system has failed
2. the most recent event for any of it's devices has failed
3. the most recent event for any parameters of it's devices have failed
我编写了这个(可怕的)SQL 查询,当它在控制台中执行时,将系统作为数组返回:
"SELECT * FROM Systems WHERE Systems.id IN (SELECT Devices.system_id FROM Devices WHERE Devices.id IN (SELECT Parameters.device_id FROM Parameters JOIN EVENTS ON Parameters.id=Events.eventable_id WHERE Events.okay ='f')) OR Systems.id IN (SELECT Devices.system_id FROM Devices JOIN Events ON Devices.id=Events.eventable_id WHERE Events.okay='f')")
我需要在 System 模型或类方法上定义一个范围以返回“失败”系统的列表。你能帮忙吗?
【问题讨论】:
标签: sql ruby-on-rails ruby activerecord scope