Search code examples
ruby-on-railsoptgroup

How to make optgroup label selectable in Rails form?


I have created the following select using the option_groups_from_collection_for_select form helper in Rails as part of a search feature.

<select>
  <option>All Categories</option>
  <optgroup label="Garden">
    <option value="1">Garden Accessories</option>
    <option value="2">Gardens Random</option>
    <option value="3">Sheds</option>
    <option value="4">Playsets</option>
  </optgroup>
<select> 

The problem is, I want a user to be able to search all of the "Garden" sub-categories at once, but as "Garden" is a label, this does not work, it forces the user to pick one of the sub-categories.

One idea is to somehow be able to add a <option>All Garden<option> tag within the optgroup, but not sure how to inject this into the list.

My search form has no room to add a second sub-category select box.


Solution

  • I figured this out,

    In the method I am using to get the child-categories for the optgroup, I just append the current model / category to the array of child categories returned from the AR find call and it works a treat.

    .unshift(self.dup)
    

    Hope this helps someone.