我目前正在开发一个用于管理设备租借的Web应用程序。我的设备属于设备类型,并与租借相关联,开始日期和结束日期。
我现在想要显示给定范围内每天每种类型的设备数量,如下所示:
| Device Type: | 01.01 | 02.01 | 03.01 | 04.01 | 05.01 |
--------------------------------------------------------
|Laptop | 10 | 10 | 10 | 5 | 5 |
|Mobile Phone | 30 | 25 | 25 | 10 | 10 |
目前,我发现任何指定日期的可用设备如下:
相应的代码如下所示:
def Device.available_devices(start_date, end_date)
other_rentals = Rental.where("outbound_delivery_date <= ? AND inbound_delivery_date >= ?", end_date, start_date)
unavailable_devices = DeviceRental.where("rental_id IN (?)", other_rentals.map(&:id))
if other_rentals.any? && unavailable_devices.any?
@available_devices = Device.where("NOT devices.id IN (?)", unavailable_devices.map(&:device_id)).joins(:device_type).order("device_types.name")
else
@available_devices = Device.all
end
end
现在在表格中显示这意味着通过1.-3。对于每个日期,因此导致大量的数据库查询似乎效率低下。任何人都能指出我如何以更有效的方式获得这些数据的正确方向吗?
答案 0 :(得分:0)
您可以使用NOT IN
available_devices = Device.where('devices.id NOT IN (SELECT device_id FROM device_rentals WHERE rental_id IN (SELECT rentals.id from rentals WHERE outbound_delivery_date <= ? AND inbound_delivery_date >= ?))', end_date, start_date)
得到计数...
available_devices.count