加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

数组 – Rails – grouped_options_for_select

发布时间:2020-12-17 01:47:47 所属栏目:百科 来源:网络整理
导读:我在使用groups_options_for_select填充选项组的Rails中的选择框时遇到一些困难. 我目前有3个实例变量,我想将其添加到分组选择框的一个整个分组数组中. 例如,我有: @fruits (which contains the object(s)) --- !ruby/object:Fruits attributes: id: 2 name
我在使用groups_options_for_select填充选项组的Rails中的选择框时遇到一些困难.

我目前有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>

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,但我继续遇到一堆错误,我不确定这样做的正确方法.

解决方法

grouped_options_for_select方法确实是正确的.
由于您尚未提供代码,因此应该会产生所需的分组选项:

grouped_options_for_select [['Fruits',@fruits.collect {|v| [ v.name,v.id ] }],['Veggies',@veggies.collect {|v| [ v.name,['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(...)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读