我在我的模型中使用了此方法,以允许我的视图显示与车辆相关的所有设备。我是否应该使用find_each来检查批记录,如果是这样,我将如何分解这种方法来使用它?find_each活动记录查询
def equip(vehicle)
equip = Vehicle.find_by_id(vehicle).equipments.
where("vehicle_id = ?", vehicle).all
end
我在我的模型中使用了此方法,以允许我的视图显示与车辆相关的所有设备。我是否应该使用find_each来检查批记录,如果是这样,我将如何分解这种方法来使用它?find_each活动记录查询
def equip(vehicle)
equip = Vehicle.find_by_id(vehicle).equipments.
where("vehicle_id = ?", vehicle).all
end
不要在最后使用.all,它会在它被调用时触发查询,并且会成为一个痛苦的表现。
此外,你应该使用这个语法(Rails 3中):
def equip(vehicle)
equip = Equipment.where(vehicle_id: vehicle.try(:id) || vehicle)
end
利用这一点,你只使用设备型号,将只使用equipments
SQL表(而不是2或更多)。
# This line
vehicle.try(:id) || vehicle
# Allows you to pass both a Vehicle object or a vehicle id to your method
另外,如果你已经有车的情况下,你可以使用:
def equip(vehicle)
equip = Vehicle.where(id: vehicle).first.equipments
# or with your syntax:
equip = Vehicle.find(vehicle).equipments
end
实现它,但得到未定义的方法ID。当我拿出vehicle.try(:id)时,它工作得很好。另外,我应该考虑find_each?我现在对它的理解是,这会将整个设备表加载到内存中,然后开始处理 – 2013-04-29 20:15:55
@SamThode更新;) – MrYoshiji 2013-04-29 20:18:30
是'vehicle'车辆的ID? – Deekor 2013-04-29 20:09:50
@Deekor - 是的,当我从视图中调用该方法时,我正在传入vehicle.id。它通过设备表查找并查找分配给给定车辆的所有设备。 – 2013-04-29 20:10:46
下面的答案应该足够了。只是一个侧面说明,你应该可以直接调用'Vehicle.find(vehicle)..'而不是'find_by_id' – Deekor 2013-04-29 20:16:38