您通常如何在Rails中对项目进行排序? [英] How do you normally sort items in Rails?

查看:66
本文介绍了您通常如何在Rails中对项目进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Rails的小示例Rails应用程序,它可以查看和编辑出售给各个客户的虚拟票证.在def index内部的tickets_controller.rb中,我有这条由脚手架生成的标准线:

I have a little example Rails app called tickets, which views and edits fictional tickets sold to various customers. In tickets_controller.rb, inside def index, I have this standard line, generated by scaffolding:

@tickets = Ticket.find(:all)

要按名称对票证进行排序,我发现了两种可能的方法.您可以这样操作:

To sort the tickets by name, I have found two possible approaches. You can do it this way:

@tickets = Ticket.find(:all, :order => 'name')

...或这种方式:

@tickets = Ticket.find(:all).sort!{|t1,t2|t1.name <=> t2.name}

(提示:Ruby文档解释了sort!会修改正在排序的数组,而不是单独的sort,它会返回已排序的数组,但原始数组保持不变).

(Tip: Ruby documentation explains that sort! will modify the array that it is sorting, as opposed to sort alone, which returns the sorted array but leaves the original unchanged).

您通常使用什么策略?什么时候可以使用.sort!:order => 'criteria'语法?

What strategy do you normally use? When might you use .sort! versus the :order => 'criteria' syntax?

推荐答案

对于数据库可以完成的任何简单操作(即基本字母顺序或时间顺序),请使用:order => 'criteria'.假设您有正确的索引,那么它可能比让您的Ruby代码快得多.

Use :order => 'criteria' for anything simple that can be done by the database (ie. basic alphabetical or chronological order). Chances are it's a lot faster than letting your Ruby code do it, assuming you have the right indexes in place.

我唯一认为您应该使用sort方法的情况是,如果您有一个在运行时计算且未存储在数据库中的复杂属性,例如基于好坏数的可信赖性值"回应之类的.在这种情况下,最好使用sort方法,但是请注意,如果分页到位,这会搞砸(每个页面将按顺序排列ITS结果,但是整个页面集将不完整订单).

The only time I could think you should use the sort method is if you have a complex attribute that's calculated at run-time and not stored in the database, like a 'trustworthiness value' based off number of good/bad responses or something. In that case it's better to use the sort method, but be aware that this will screw things up if you have pagination in place (each page will have ITS results in order, but the set of pages as a whole will be out of order).

这篇关于您通常如何在Rails中对项目进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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