0
votes

I want to use form.select to create an optgroup with options. I'm not able to see anything in the dropdown other than 'Select a category'. The result HTML shows that it's nesting a select tag inside another. Is there an option to not generate the innermost select tag via grouped_collection_select?

products/_form.html.erb

<%= form.select :category_id, grouped_collection_select(:product, :category_id, Category.top_level, :sub_categories, :name, :id, :name),
                            { prompt: 'Select a category'},
                            { id: :product_category } %>

category.rb

has_many :products
has_many :sub_categories, class_name: "Category", foreign_key: :parent_id
scope :top_level, -> { where(parent_id: nil) }

product.rb

belongs_to :category

Result HTML

<select id="product_category" name="product[category_id]">
<option value="">Select a category</option>


<select name="product[category_id]" id="product_category_id">
<optgroup label="Category 1">
<option value="4">Sub Category A</option>
<option value="5">Sub Category B</option>
</optgroup>

<optgroup label="Category 2">
<option value="6">Sub Category A</option>
<option value="7">Sub Category B</option>
</optgroup>

</select>
</select>
1

1 Answers

1
votes

For anybody else interested, the below syntax gave me the expected HTML output.

<%= form.grouped_collection_select(:category_id, Category.top_level, :sub_categories, :name, :id, :name,
                                { prompt: 'Select a category'},
                                { id: :product_category }) %>