Rails - grouped_options_for_select
Asked Answered
B

1

6

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.

Bismuthinite answered 3/2, 2014 at 8:15 Comment(0)
I
20

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(...)
Impious answered 3/2, 2014 at 10:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.