Victor
Victor

Reputation: 13378

Retrieve a set of records with SQL, then order them using Rails

Using Rails 3.2 and MariaDB. My table has 500,000 rows. In usual query, we will add the order clause in it, like this:

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

If we remove the order, the load time is greatly reduced:

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

Is it possible to first retrieve the @shops 100 records, then use Rails to order them by overall_rating DESC without involving SQL? Or, separate the queries to 2 parts: first retrieve 100 records, then order that set of records. This can greatly improve the performance.

Upvotes: 1

Views: 58

Answers (1)

Javid Jamae
Javid Jamae

Reputation: 9009

Yes, sorting a collection is part of Ruby's Enumerable mixin.

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

Upvotes: 1

Related Questions