A product belogs_to category. A category has_many products
I need a select tag that includes the optgroup tag.
So basically, I need my HTML markup to something similar to pseudo code:
<select name="product" class="products">
<option value=""></option>
<optgroup label="Cheese">
<option value="1">cheese 1</option>
<option value="2">cheese 2</option>
<option value="3">cheese 3</option>
</optgroup>
<optgroup label="Juices">
<option value="3">juice 1</option>
<option value="4">juice 2</option>
<option value="5">juice 3</option>
</optgroup>
</select>
Based on my models, how would I generate the array to put into grouped_options_for_select? For example, what is the best approach to generate grouped_options?
<%= select_tag 'product', grouped_options_for_select(grouped_options), :include_blank => true , :id => nil, :class => 'product' %>
Controller:
@products = Product.all(:include => :category)
@grouped_options = @products.inject({}) do |options, product|
(options[product.category.name] ||= []) << [product.name, product.id]
options
end
View:
<%= select_tag 'product', grouped_options_for_select(@grouped_options), :include_blank => true , :id => nil, :class => 'product' %>
For Rails 4
Model:
class Category < ActiveRecord::Base
has_many :products
end
class Product < ActiveRecord::Base
belongs_to :category
end
Controller:
@grouped_options = Category.all.map {
|category| [category.name,
category.products.map {
|product| [product.name,product.id]}]}
View:
<%= select_tag(:product, grouped_options_for_select(@grouped_options))%>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With