1

我正在使用 Ruby on Rails 从 mySQL 数据库中获取数据,如下所示:

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

2 回答 2

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...">]
}

遍历这个哈希应该很容易。请注意,某些字母可能会丢失。

于 2013-08-21T19:00:11.643 回答
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>  
于 2013-08-29T20:35:28.227 回答