【问题标题】:Rails - grouped_options_for_selectRails - grouped_options_for_select
【发布时间】:2016-12-22 16:48:00
【问题描述】:

我在使用 grouped_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,但我继续遇到一堆错误,我不确定执行此操作的正确方法。

【问题讨论】:

    标签: arrays ruby-on-rails-4 optgroup


    【解决方案1】:

    grouped_options_for_select 方法确实是正确的方法。 由于您没有提供代码,这应该会产生您想要的分组选项:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-07
      • 2018-09-29
      相关资源
      最近更新 更多