DaudiHell DaudiHell - 5 months ago 23
Ruby Question

The right method to display sub-categories for f.select in rails app?

I'm building an Rails app were the user must select type of business via


I've used
before without any problems. but now I have to add sub-categories to the select.

In my app the user have to select one category and then have to select a sub-category according to the parent category.

How would I do it? is it possible?

This is basically what I need:

---category 1----




----Category 2 ----




----Category 3 ----




I'm not sure how I would manage to do this, any suggestion would be great.

I've been googling around without success

I haven't start building this yet, I wanted to check here first if someone had a solution to this


This can definitely be done. You can use the standard rails form or the simple_form gem to do this.

For example if you had categories and items to display, your standard rails form would look like this:

<%= form_for @item do |f| %>

    <%= f.grouped_collection_select(:category_id, Category.order(:name), 
                          :items, :name, :id, :title, 
                          include_blank: "Please Choose...") %>
<% end %>

This displays the main categories, and then the subcategories (items in this case) in each category. Its output looks like this, in which accessories, canon camera etc are the main categories, and manfrotto tripod, canon 5D3 are the sub categories.:


It is similar to the html optgroup tag which looks like this:

 <optgroup label="Group 1">
   <option>Option 1.1</option>
 <optgroup label="Group 2">
   <option>Option 2.1</option>
   <option>Option 2.2</option>
 <optgroup label="Group 3" disabled>
   <option>Option 3.1</option>
   <option>Option 3.2</option>
   <option>Option 3.3</option>

Which produces:


Obviously you would have to modify this to fit your project, but it can definitely be achieved.