让我们说我有一个通用模型,只需要#34; Model",只有几千个实例。现在我在页面上显示Model.all,如下所示:
<% Model.all.order(:name).each do |model| %>
<%= model.name %>
<% end %>
但我考虑用第一个字母将其分开,如下所示:
A
<% Model.where(name.chars.first: "A").order(:name).each do |model| %>
<%= model.name %>
<% end %>
B
<% Model.where(name.chars.first: "B").order(:name).each do |model| %>
<%= model.name %>
<% end %>
C
<% Model.where(name.chars.first: "C").order(:name).each do |model| %>
<%= model.name %>
<% end %>
...
等等。加载此方法需要的时间明显长于简单Model.all
吗?
答案 0 :(得分:0)
您可以遍历things
集合并在需要时插入一个起始字母:
things = Thing.order(:name)
current_letter = 'A'
things.each do |thing|
if thing.name.chars.first != current_letter
current_letter = thing.name.chars.first
puts current_letter
end
puts thing.name # just as an example
end