使用SQL检索一组记录,然后使用Rails对它们进行排序

使用Rails 3.2和MariaDB。 我的表有500,000行。 在通常的查询中,我们将在其中添加order子句,如下所示:

 # takes 4000ms to load, returns 100 records @shops = Shop.where(:shop_type => 'fashion').order('overall_rating DESC') 

如果我们删除order ,则加载时间会大大减少:

 # takes 20ms to load, returns 100 records @shops = Shop.where(:shop_type => 'fashion') 

是否可以首先检索@shops 100记录,然后使用Rails通过overall_rating DESC对它们进行overall_rating DESC而不涉及SQL? 或者,将查询分为两部分:首先检索100条记录,然后订购该组记录。 这可以大大提高性能。

是的,排序集合是Ruby的Enumerable mixin的一部分。

 @shops = Shop.where(:shop_type => 'fashion') @shops.sort! { |a,b| b.overall_rating <=> a.overall_rating }