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

孤街醉人 提交于 2019-12-10 14:25:17

问题


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,


回答1:


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


来源:https://stackoverflow.com/questions/22049725/re-sorting-active-records-in-rails-without-re-querying-the-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!