Ruby/Active Record:自定义排序顺序 [英] Ruby / Active Record: custom sorting order
问题描述
我正在开发一个 rails 3.2 ruby 1.9.2 项目.
I'm working on a rails 3.2 ruby 1.9.2 project.
我使用经典从数据库中获取一些值:
I get some values from database with a classic:
designators = Model.find()
我用(简化代码)显示它:
And I show it in view with (simplified code):
<table class="rwy_modes_table" cellspacing='0'>
<% designators.each do |info_design| %>
<tr id="rwy_mode_<%=info_design.id%>">
<td class="spacer"><%= info_design.try(:designator) %></td>
</tr>
<% end %>
</table>
值例如:3L、3C、3R.(L 代表左,C 代表中心,4 代表右).我想要排序的值,例如:3L、3C、3R 而不是 3C、3L、3R
Values are for example: 3L, 3C, 3R. (L for Left, C for Center, 4 for Right). I would like values ordered such as: 3L, 3C, 3R and not 3C, 3L, 3R
我不知道如何定义这个自定义订单.有什么想法吗?
I don't know how to define this custom order. Any idea ?
推荐答案
试试这个:
(app/models/designator.rb)
# determines the sort value for based on my_attribute.
# designators should be in the order 'l', 'c', 'r' - regardless of any preceeding numeral
def sort_val
return 0 if self.my_attribute =~ /l/i
return 1 if self.my_attribute =~ /c/i
return 2 if self.my_attribute =~ /r/i
end
(app/helpers/designators_helper.rb)
def sorted_designators(designators)
designators.sort{|a, b| a.sort_val <=> b.sort_val }
end
您可以在视图中进行排序的位置
Where you can do sorting in your view
(app/views/...)
sorted_designators(designators).each do |design|
或者,您可以将其移动到模型文件中的静态方法中,以便在您的视图之外轻松排序
Alternately, you can move this to a static method in your model file, for easy sorting outside your view
(app/models/designator.rb)
def self.sorted_designators(designators)
designators.sort{|a, b| a.sort_val <=> b.sort_val }
end
并像这样在控制器中使用它们
and use them in your controller like this
app/controllers...
@designators = Designator.sorted_designators(designators)
注意:这是内存中的排序,因此请注意 O(n) db 查询,具体取决于您排序/访问此对象的方式
Note: this is an in-memory sort, so watch for O(n) db queries depending on how you sort / access this object
另见:https://stackoverflow.com/a/14282353/811255 使用 Comparable 模块(可能更清洁的解决方案)
See also: https://stackoverflow.com/a/14282353/811255 for using the Comparable module (probably a cleaner solution)
这篇关于Ruby/Active Record:自定义排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!