Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re sorting active records in rails without re querying the database?

For example lets assume I have a model called Products and in the Products controller I have the following code for the product_list view to display products sorted.

@products = Product.order(params[:order_by])

And lets imagine in the product_list view the user is able to sort by price, rating, weight etc using a dropdown. The products in the database won't change frequently.

What i'm having a hard time understanding is whether rails will have to query each time when the user selects a new order_by filter or will rails somehow able to cache the active records for re-sorting on the server side? Is there a way to write it so rails won't re query the result if the user sorts? (ie if the product table does not change frequently so there is no point in making a query if the user just want to sort by a different variable)

Thanks,

like image 656
zjwang Avatar asked Feb 26 '14 18:02

zjwang


1 Answers

You are probably looking for the sort_by method. It will allow you to sort a collection on the server side without using any active record query.

This code result :

@products = Product.all
@products = @products.sort_by {|product| product.name} # Ruby Sorting

should be the same as

@products = Product.order(:name) # SQL sorting
like image 95
Uelb Avatar answered Oct 21 '22 14:10

Uelb