Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - grouped_options_for_select

I am having some difficulty populating a select box in Rails with option groups using grouped_options_for_select.

I currently have 3 instance variables that I would like to add to one entire grouped array for the grouped select box.

For example, I have:

@fruits (which contains the object(s))
   --- !ruby/object:Fruits
      attributes:
      id: 2
      name: Banana

@veggies (which contains the object(s))
   --- !ruby/object:Veggies
      attributes:
      id: 23
      name: Celery
   --- !ruby/object:Veggies
      attributes:
      id: 24
      name: Carrots

@junk_food (which contains the object(s))
   --- !ruby/object:Junk
      attributes:
      id: 11
      name: Snickers
   --- !ruby/object:Junk
      attributes:
      id: 12
      name: Ice Cream

My question is: How do I take these 3 instance variables and turn them into a grouped select, like:

  <select>
    <optgroup label="Fruits">
      <option value="2">Banana</option>
    </optgroup>
    <optgroup label="Veggies">
      <option value="23">Celery</option>
      <option value="24">Carrots</option>
    </optgroup>
    <optgroup label="Junk">
      <option value="11">Snickers</option>
      <option value="12">Ice Cream</option>
    </optgroup>
  </select>

food_controller.erb

@fruits = Fruit.all
@veggies = Veggies.all
@junk_food = JunkFood.all

# Then, I'd create the array here using the items above?

I know I am supposed to be using grouped_items_for_select, but I continue running into a bunch of errors and I am not sure of the proper way to do this.

like image 260
Dodinas Avatar asked Feb 03 '14 08:02

Dodinas


1 Answers

The grouped_options_for_select method indeed is the correct one. Since you haven't provided code, this should result in the grouped options you want:

grouped_options_for_select [['Fruits',  @fruits.collect {|v| [ v.name, v.id ] }],
                            ['Veggies', @veggies.collect {|v| [ v.name, v.id ] }],
                            ['Junk',    @junk_food.collect {|v| [ v.name, v.id ] }]]

Which can be used to create the dropdown:

select_tag 'Food', grouped_options_for_select(...)

or with form_helper:

f.select :food_attribute, grouped_options_for_select(...)
like image 171
Rescribet Avatar answered Oct 15 '22 12:10

Rescribet