DaudiHell DaudiHell - 2 months ago 10
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

f.select
.

I've used
f.select
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----

--sub-cat-1a--

--sub-cat-1b--

--sub-cat-1c--

----Category 2 ----

--sub-cat-2a--

--sub-cat-2b--

--sub-cat-2c--

----Category 3 ----

--sub-cat-3a--

--sub-cat-3b--

--sub-cat-3c--


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

Answer

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.:

Category1

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

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

Which produces:

Category2

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