[英]find_each Active Record Querying
I have this method in my model to allow my view to display all equipment associated with a vehicle. 我的模型中有此方法,以允许我的视图显示与车辆关联的所有设备。 Should I be using find_each to check batches of records, and if so, how would I break this method down to use it?
我是否应该使用find_each来检查记录批次,如果是,我将如何分解此方法以使用它?
def equip(vehicle)
equip = Vehicle.find_by_id(vehicle).equipments.
where("vehicle_id = ?", vehicle).all
end
Don't use .all at the end, it will trigger the query when its called and will be a pain as perfomances. 不要在末尾使用.all,它会在调用查询时触发查询,并且会给您带来痛苦。
Also, you should use this syntax (Rails 3): 另外,您应该使用以下语法(Rails 3):
def equip(vehicle)
equip = Equipment.where(vehicle_id: vehicle.try(:id) || vehicle)
end
Using this, you only use the Equipment model, which will just use the equipments
SQL table (not 2 or more). 使用此方法,您仅使用设备模型,该模型将仅使用
equipments
SQL表(而不是2个或更多)。
# This line
vehicle.try(:id) || vehicle
# Allows you to pass both a Vehicle object or a vehicle id to your method
Also, if you have already an instance of vehicle, you could use: 另外,如果您已经有一个Vehicle实例,则可以使用:
def equip(vehicle)
equip = Vehicle.where(id: vehicle).first.equipments
# or with your syntax:
equip = Vehicle.find(vehicle).equipments
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.