导轨 - grouped_options_for_select [英] Rails - grouped_options_for_select

查看:168
本文介绍了导轨 - grouped_options_for_select的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些困难,使用Rails中填充选择框选项组 grouped_options_for_select

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

我现在有3个实例变量,我想补充一个整个​​分组阵列的组合选择框。

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

例如,我有:

@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个实例变量,把它们变成一个分组的选择,如:

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?

我知道我应该使用到 grouped_items_for_select ,但我继续运行成一堆错误,我不知道的正确的方式来做到这一点。

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.

任何帮助将是巨大的!

感谢您。

推荐答案

grouped_options_for_select 方法确实是正确的。
既然你没有提供code,这将导致你想要的分组选项:

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

或form_helper:

or with form_helper:

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

这篇关于导轨 - grouped_options_for_select的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆