Rails - grouped_options_for_select

2019-05-10 00:01发布

问题:

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.

回答1:

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(...)