Create a select tag including related models

Hi!

I have categories and subcategories. Now I want to create a select tag with this data so a user can select either a category or a subcategory. What I tried first was to use grouped_collection_select and use the main categories as groups and list the subcategories inside. Visually, this is the goal. The problem with this is that I need to be able to select the main categories as well and not only the subcategories.

So, now I want to list them like this:

Cat1 -- Subcat1 -- Subcat2 Cat2 -- Subcat...

How can I implement this? I’ve tried using the collection_select() method but I don’t get it right.

@menu_categories contains the main categories and the subcategories are in some_category.subcategories

Any help is very appreciated.

Thanks!

Linus Pettersson wrote in post #1065179:

Hi!

I have categories and subcategories. Now I want to create a select tag
with
this data so a user can select either a category or a subcategory. What
I
tried first was to use grouped_collection_select and use the main
categories as groups and list the subcategories inside. Visually, this
is
the goal. The problem with this is that I need to be able to select the
main categories as well and not only the subcategories.

So, now I want to list them like this:
<select>
  <option data-foo="abc">Cat1</option>
  <option data-foo="das">-- Subcat1</option>
  <option data-foo="fsd">-- Subcat2</option>
  <option data-foo="asda">Cat2</option>
  <option data-foo="das">-- Subcat...</option>
....

How can I implement this? I've tried using the collection_select()
method
but I don't get it right.

Have you tried "option_groups_from_collection_for_select"?

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-option_groups_from_collection_for_select

No…but that’s generating the same as grouped_collection_select() but without the wrapping tag so that doesn’t work…