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