Frage

I am getting data from my mySQL database with Ruby on Rails like that:

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

Now, I would like to sort this data in the view file like that:

 <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

How can I achieve that ?

War es hilfreich?

Lösung

You could group the data:

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

This returns a hash like:

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

Looping through this hash should be quite easy. Note that some letters could be missing.

Andere Tipps

Thank you very much for all of your help. Zippie provided amazing solution! Here is the implementation and iterating over hash for everyone:

<% 
 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>  
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top