Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 轨道-分组的\u选项\u用于\u选择_Arrays_Ruby On Rails 4_Optgroup - Fatal编程技术网

Arrays 轨道-分组的\u选项\u用于\u选择

Arrays 轨道-分组的\u选项\u用于\u选择,arrays,ruby-on-rails-4,optgroup,Arrays,Ruby On Rails 4,Optgroup,我在Rails中使用grouped\u options\u for\u select填充带有选项组的选择框时遇到了一些困难 我目前有3个实例变量,我想将它们添加到分组选择框的整个分组数组中 例如,我有: @fruits (which contains the object(s)) --- !ruby/object:Fruits attributes: id: 2 name: Banana @veggies (which contains the obj

我在Rails中使用
grouped\u options\u for\u select
填充带有选项组的选择框时遇到了一些困难

我目前有3个实例变量,我想将它们添加到分组选择框的整个分组数组中

例如,我有:

@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
我的问题是:如何将这3个实例变量转换为分组选择,如:

  <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>

我知道我应该使用
grouped\u items\u作为\u select
,但我仍然会遇到一系列错误,我不确定这样做的正确方法。

用于\u select的
grouped\u options\u方法确实是正确的。
由于您没有提供代码,这将导致您需要的分组选项:

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 ] }]]
可用于创建下拉列表:

select_tag 'Food', grouped_options_for_select(...)
或使用form_helper:

f.select :food_attribute, grouped_options_for_select(...)
f.select :food_attribute, grouped_options_for_select(...)