Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate array for grouped_options_for_select based on models

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' %>
like image 544
Christian Fazzini Avatar asked May 11 '11 12:05

Christian Fazzini


2 Answers

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' %>
like image 192
BitOfUniverse Avatar answered Sep 27 '22 19:09

BitOfUniverse


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))%>
like image 37
Manolo Pirolo Avatar answered Sep 27 '22 17:09

Manolo Pirolo