Ruby-on-rails 你通常如何在 Rails 中对项目进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/657654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you normally sort items in Rails?
提问by Nathan Long
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 的 Rails 应用程序示例,它可以查看和编辑出售给不同客户的虚构门票。在 ticket_controller.rb 里面def index,我有这个标准行,由脚手架生成:
@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')
... or this way:
……或者这样:
@tickets = Ticket.find(:all).sort!{|t1,t2|t1.name <=> t2.name}
(Tip: Ruby documentation explains that sort!will modify the array that it is sorting, as opposed to sortalone, which returns the sorted array but leaves the original unchanged).
(提示:Ruby 文档解释说sort!将修改它正在排序的数组,而不是sort单独返回排序后的数组但保持原始数组不变)。
What strategy do you normally use? When might you use .sort!versus the :order => 'criteria'syntax?
你通常使用什么策略?你什么时候可以使用.sort!vs:order => 'criteria'语法?
回答by Luke
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.
使用:order => 'criteria'了简单的东西可以由数据库(即基本字母顺序或时间顺序)来完成。假设您有正确的索引,它可能比让您的 Ruby 代码执行此操作要快得多。
The only time I could think you should use the sortmethod 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 sortmethod, 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).
我认为您应该使用该sort方法的唯一时间是,如果您有一个在运行时计算而不存储在数据库中的复杂属性,例如基于好/坏响应数量的“可信度值”等。在这种情况下,最好使用该sort方法,但请注意,如果您有分页,这会搞砸(每个页面都会按顺序显示 ITS 结果,但整个页面集将无序)。
回答by John Topley
I specify an order in the ActiveRecord finder or in the model association because sorting using SQL is faster. You should take advantage of the features offered by the RDBMS when you're able to do so.
我在 ActiveRecord finder 或模型关联中指定了一个顺序,因为使用 SQL 进行排序更快。当您能够这样做时,您应该利用 RDBMS 提供的功能。

