将Model.all拆分成不同的起始字母是否会减慢加载时间?

时间:2015-02-05 05:05:35

标签: ruby-on-rails ruby database ruby-on-rails-4 activerecord

让我们说我有一个通用模型,只需要#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吗?

1 个答案:

答案 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