Topic: Select Menu with Groups
I am attempting to create a select menu with groups from some static content in my model. I am having trouble figuring out how to get the select form helper to implement the optgroup tag to group the options.
Basically I am trying to generate the following html code:
<select id="order_drink_type" name="order[drink_type]">
<optgroup label="Soda">
<option value="HazelnutSoda">Hazelnut</option>
<option value="BirchBeerSoda">Birch Beer</option>
<option value="CoconutSoda">Coconut</option>
</optgroup>
<optgroup label="Juice">
<option value="BlueberryJuice">Blueberry</option>
<option value="StrawberryJuice">Strawberry</option>
</optgroup>
</select>
From the following model definition:
def drink_types
['Soda' => [
{'name' => 'HazelnutSoda', 'display' => 'Hazelnut'},
{'name' => 'BirchBeerSoda', 'display' => 'Birch Beer},
{'name' => 'CoconutSoda', 'display' => 'Coconut'}
],
'Juice => [
{'name' => 'BlueberryJuice', 'Blueberry'},
{'name' => 'StrawberryJuice', 'Strawberry'}
]
]
end
I would like to use a simple select form helper inside a form_for tag if that is possible. For example:
<% form_for @order do |f| %>
<%= f.select :drink_type, @order.drink_types %>
<% end %>
This of course only lists the drink categories as options rather than listing the actual drink types as options grouped by the categories using the optgroup tag. Is there an easy way to implement this with rails or am I going to have to just hard code it in the HTML?
Thanks.