包括数组的关联

时间:2013-12-22 16:59:44

标签: ruby-on-rails

使用Rails 3.2,我有以下原始代码:

nearby_spots = current_spot.nearbys(10, :order => 'overall_rating 
DESC').where(:spot_type => spot_type).includes(:photos).first(5)

出于某些性能原因,我必须将代码分成以下内容:

# retrieve all records without any order
x = current_spot.nearbys(10, :order => false).where(:spot_type => spot_type)

# sort by overall_rating using Rails instead of SQL, and take first 5
nearby_spots = (x.sort! { |a,b| b.overall_rating <=> a.overall_rating }).first(5)

nearby_spots是一个对象数组。如何像原始文件一样急切加载photos.includes仅适用于类,而非数组。

1 个答案:

答案 0 :(得分:1)

使用preloader,添加以下行:

ActiveRecord::Associations::Preloader.new(nearby_spots, :photos).run()