0

I have an array like this:

@airports = [
  ['Malaysia', 'Alor Setar', 'AOR'],
  ['Malaysia', 'Bintulu', 'BTU'],
  ['Malaysia', 'Ipoh', 'IPH'],
  ['Malaysia', 'Johor Bahru', 'JHB'],
  ['Indonesia', 'Kuching', 'KCH'],
  ['Indonesia', 'Labuan', 'LBU'],
  ['Indonesia', 'Langkawi', 'LGK'],
  ['Indonesia', 'Miri', 'MYY'],
  ['Indonesia', 'Penang', 'PEN'],
]

then in my view:

<select name="from" class="form-control select2">
    <% @airports.each do |airport| %>
      <optgroup label="<%= airport[0] %>">
        <option value="<%= airport[2] %>" <%= @params[:from] == airport[2] ? "selected" : "" %>>
          <%= "#{airport[1]} (#{airport[2]})" %>
        </option>
      </optgroup>
    <% end %>
  </select>

which gives the result like this:

Result

How can I group it for each country? I mean like this:

Malaysia
Alor Setar
Bintulu
Ipoh
Johor

Indonesia
Kuching
Labuan
Langkawi
Penang
Miri

1 Answer 1

3

In your view, you can do something like:

<% countries = @airports.group_by{|a| a.first} %>
<% countries.each do |country, airport| %>
  <optgroup label="<%= country %>">
    <% airport.each do |a| %>
      <option value="<%= a[1] %>"></option>
    <% end %>
  </optgroup>
<% end %>

PS: This is just to give you a rough idea, I'm missing the logic you used for <option value> in my example. Hope you can fix it accordingly.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. This method fixed my problem. Will accept your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.