使用相同 table 的列进行集合分组

Collection Group by using same table's column

我在数据库中有如下记录

Table :Role
================
id:    sub_category:       main_category:
1      john                student
2      somaina             student
3      sharif              teacher
4      Imran               student
5      Haider              teacher
6      Vijay               student

我想在select框中显示这条记录,分组如下

<select>
  <optgroup label="Teacher">
    <option value="3">Sharif</option>
    <option value="5">Haider</option>
  </optgroup>
  <optgroup label="Student">
    <option value="1">John</option>
    <option value="2">Somaina</option>
    <option value="4">Imran</option>
    <option value="6">Vijay</option>
  </optgroup>
</select>

你可以用 Enumerable 做到这一点#group_by:

<select>
  <% Role.all.group_by(&:main_category).each do |main_category, category_records| %>
    <optgroup label="<%= main_category %>">
      <% category_records.each do |record| %>
        <option value="<%= record.id %>">
          <%= record.sub_category %>
        </option>
      <% end %>
    </optgroup>
  <% end %>
</select>

https://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-group_by