2013-08-21 56 views
1

我從我的MySQL數據庫使用Ruby獲得on Rails的數據那樣:Rails - 如何創建按字母順序排列的系統?

def all_specs 
    Specialization.order("title ASC").all; 
end 

現在,我想以按這樣的視圖文件這樣的數據:

<div class="nav-column"> 
    <h3>A</h3> 
    <ul class="submenu"> 
     <li><a href="#">All data that has title that starts with A</a></li> 
    </ul> 
</div> 

<div class="nav-column"> 
    <h3>A</h3> 
    <ul class="submenu"> 
     <li><a href="#">All data that has title that starts with B</a></li> 
    </ul> 
</div> 

and so on from A-Z 

我怎樣才能實現那個?

回答

4

你可以組數據:

specs = Specialization.order("title ASC") 
specs_by_first_letter = specs.group_by { |spec| spec.title[0] } 

這將返回如哈希:

{ 
    "A" => [<Specialization title:"A...">, <Specialization title:"A...">], 
    "B" => [<Specialization title:"B...">, <Specialization title:"B...">], 
    ... 
    "Z" => [<Specialization title:"Z...">, <Specialization title:"Z...">] 
} 

該散列循環應該是很容易的。請注意,有些字母可能會丟失。

+0

偉大的思想! :) – Zippie

0

非常感謝您的幫助。 Zippie提供了驚人的解決方案! 下面是執行和遍歷散給大家:

<% 
institutions_c = all_institution_categories 
inst_by_first_letter = institutions_c.group_by { |inst| inst.title[0] } 
%> 

<% inst_by_first_letter.each do |key, value| %> 
    <div class="nav-column"> 
      <h3><%= key %></h3> 
      <ul class="submenu"> 
       <% value.each do |cat| %> 

        <li><%= link_to cat.title, institutions_path(:categories => cat.id), :title => cat.title %></li> 

       <% end %> 
      </ul> 
    </div>