Select a drop-down list and each block - Ruby / Rails

I have a simple block eachthat accepts each category and createsoption

@categories = Category.all

<select id="bike_category_filter" multiple="multiple">
  <% @categories.each do |c| %>
    <option value="<%= c.name %>"><%= c.name %></option>
  <% end %>

What I would like with categories Men and Women(so c.name) to surround them with a tag <optgroup>. How could I achieve this, a link to a resource or an explanation of where to look would be enough, it’s not necessary to search for someone to give me an answer

The desired result will look like

<select>
  <optgroup label="Gender">
    <option value="cat1">Men</option>
    <option value="cat2">Women</option>
  </optgroup>
    <option value="cat3">Cat5</option>
    <option value="cat4">Cat4</option>
</select>

thank

+4
source share
2 answers

At the end, I implemented this solution, I still feel that it can be done more elegantly

Controller

@gender_categories = Category.where(name: ['Mens', 'Womens'])
@categories = Category.where.not(name: ['Mens', 'Womens'] )

View 

<select id="bike_category_filter" multiple="multiple">
  <optgroup label="Gender">
    <% @gender_categories.each do |c| %>
      <option value="<%= c.name %>"><%= c.name %></option>
    <% end %>
  </optgroup>

  <optgroup label=" Bike Type">
    <% @categories.each do |c| %>
      <option value="<%= c.name %>"><%= c.name %></option>
    <% end %>
 </optgroup>
</select>
0
source

partition, .

:

@primary_group, @secondary_group = Category.all.partition { |c| c.name == 'Men' or c.name == 'Woman'}

<select id="bike_category_filter" multiple="multiple">
  <optgroup label="Gender">
    <% @primary_group.each do |c| %>
      <option value="<%= c.name %>"><%= c.name %></option>
    <% end %>
  </optgroup>

  <% @secondary_group.each do |c| %>
    <option value="<%= c.name %>"><%= c.name %></option>
  <% end %>
</select>
0

Source: https://habr.com/ru/post/1649282/


All Articles