Search code examples
ruby-on-railsruby-on-rails-4form-helpersgrouped-collection-select

Collection Group by using same table's column


I have record in database like below

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

I want to show this record in select box with grouping like below

<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>

Solution

  • You can do this with 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