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

For example, suppose I have a model called Products and in the Products controller I have the following code to represent product_list to display sorted products.

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

And imagine that in the product_list view the user can sort by price, rating, weight, etc. using the drop-down list. Products in the database will not change frequently.

What I hardly understand is whether rails will ask every time the user selects a new order_by filter or can the rails somehow cache active records for re-sorting on the server side? Is there a way to write it so that the rails do not request a result if the user sorts? (i.e. if the product table does not change often, so it makes no sense to make a request if the user just wants to sort by another variable)

Thanks,

+4
source share
1 answer

You are probably looking for the sort_by method. This will allow you to sort the collection on the server side without using an active write request.

Result of this code:

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

,

@products = Product.order(:name) # SQL sorting
+9

Source: https://habr.com/ru/post/1529041/


All Articles