1
使用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
只适用于一个类,而不是数组。
'includes'也适用于'的ActiveRecord :: Relation',但既然你叫''排序上的关系,它成为'Array'!所以问题是:为什么你认为这种排序方式比适当的SQL查询更有效率,就像在你的第一种方法中一样? –
原始问题在这里:http://stackoverflow.com/questions/20727131/rails-order-by-overall-rating-is-slow-for-large-set-of-records然后,我不得不让SQL接管排序,因为我有500,000行数据(http://stackoverflow.com/questions/20727363/retrieve-a-set-of-records-with-sql-then-order-them-using-rails?noredirect= 1#comment31054014_20727363),排序很慢。 – Victor