【问题标题】:Is there a more efficient way to find belongs_to records?有没有更有效的方法来查找 belongs_to 记录?
【发布时间】:2017-04-19 21:22:52
【问题描述】:
鉴于这些模型:
Class Location < ActiveRecord::Base
has_many :devices
end
和
Class Device < ActiveRecord::Base
belongs_to :location
end
我现在唯一能想到的方法是:
dev_list = []
locations = Location.near("some address") # using Geocoder :)
locations.each do |loc|
dev_list += loc.devices
end
还有比.each 循环更有效的方法吗?
【问题讨论】:
标签:
ruby-on-rails-4
associations
【解决方案1】:
在问之前应该多考虑一下,但答案很简单:
locations = Location.near("some address") # using Geocoder :)
location_ids = locations.map{|loc| loc.id}.join(',') # creates string of Location ids: "1,3,5,6,7,12,..."
dev_list = Device.where("location_id IN (#{location_ids})")
针对 1000 个位置列表进行了测试。 .each 循环大约需要 11 秒(挂钟),这种方式几乎是瞬间完成的。
请注意,在Device.where 语句中,我使用#{location_ids} 而不是更安全的["location_id IN (?)", location_ids]。这是因为使用数组条件语句会导致以下 SQL(至少对于 MySQL):
SELECT `devices`.* FROM `devices` WHERE (location_id in ('5565,5098,2293'))
仅查找 location_id 为 5565 的设备。