有没有更有效的方法来查找belongs_to记录?

时间:2017-04-19 21:22:52

标签: ruby-on-rails-4 associations

鉴于这些模型:

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循环更有效的方法?

1 个答案:

答案 0 :(得分:0)

在问之前应该多考虑一下,但答案很简单:

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的设备。