回复无需重新查询数据库排序中轨的活动记录? [英] Re sorting active records in rails without re querying the database?

查看:117
本文介绍了回复无需重新查询数据库排序中轨的活动记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如让我们假设我有一个模型,称为产品,并在产品控制器我有以下的code的所属类别视图中显示的产品来分类的。

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.

我遇到什么很难理解轨是否会对每次查询时,用户选择一个新的ORDER_BY过滤器或将轨道某种程度上能够缓存活动记录重新排序在服务器端?有没有一种方法来写它,Rails会不会重新查询结果,如果用户为哪般? (也就是说,如果产品表中不经常变化所以在做一个查询,如果用户只是想通过一个不同的变量进行排序没有任何意义)

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)

谢谢

推荐答案

您可能正在寻找sort_by方法。它可以让你在服务器端的集合进行排序,而无需使用任何活动的记录查询。

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.

这code结果:

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

应该是相同的

should be the same as

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

这篇关于回复无需重新查询数据库排序中轨的活动记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆