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,
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With