Today I Learned

hashrocket A Hashrocket project

Select options with option groups

ActionView::Helpers::FormOptionsHelper#grouped_options_for_select lets you pass in a nested array of strings, and returns a string of option tags wrapped with optgroup tags:

The first value serves as the optgroup label while the second value must be an array of options.

grouped_options = [
  ["North America",
    ["United States", "Canada"]],
  ["Europe",
    ["Denmark", "Germany", "France"]]
]

Next, simply call it from a form helper in the view, passing in your grouped options.

<%= f.select :location, grouped_options_for_select(grouped_options) %>

Voila! You should now have something like this: image

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.