ruby on rails - How to generate array for grouped_options_for_select based on models -
a product belogs_to category. category has_many products
i need select tag includes optgroup tag.
so basically, need html markup similar 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 models, how generate array put grouped_options_for_select? example, best approach 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({}) |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' %>
Comments
Post a Comment