我在数据库中有记录,如下所示
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>
<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>
答案 0 :(得分:2)
您可以使用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