【问题标题】:Rails grouped_options_for_select not populating edit actionRails grouped_options_for_select 不填充编辑操作
【发布时间】:2013-12-02 16:35:39
【问题描述】:

我有一个包含两个字段的表单,其中第二个字段取决于在第一个下拉列表中选择的内容,如果我在第一个下拉列表中选择“亚洲”,那么“日本”和“中国”将作为选项出现在第二个下拉列表中。

    .field
     = f.label :country
     = f.select :country, ['Asia', 'Europe'], :prompt => 'Select One'

   .field
     = f.label :category
     = f.select :category,grouped_options_for_select(MyModel::CATEGORIES, nil, "Please Select")

CATEGORIES 变量看起来像;

CATEGORIES = {
    'Asia'=> [ 'Japan','China'],
    'Europe'=> [ 'Ireland', 'France']
    }

这可行,但是当我进入编辑页面时,第二个下拉菜单没有预先填充存储的值,我该怎么做?

【问题讨论】:

    标签: ruby-on-rails forms ruby-on-rails-4


    【解决方案1】:

    @dax 是对的,但您需要显式设置所选值而不仅仅是属性。来自api

    selected_key - 等于标签之一的 value 属性 的值,它将具有 selected 属性集。注意:此值可能会匹配多个选项,因为您可能在多个组中具有相同的选项。然后每个都将被选中="selected"。

    你的代码应该是

    = f.select :category, grouped_options_for_select(MyModel::CATEGORIES, f.object.category)
    

    编辑

    传递给grouped_options_for_select 的最后一个参数应该传递给select,并且应该是promptinclude_blank 选项的值。

    = f.select :category,
      grouped_options_for_select(MyModel::CATEGORIES, f.object.category),
      { prompt: 'Please select' }, # here goes the select tag options
      { class: 'my-class' }        # here goes the html options
    

    【讨论】:

      【解决方案2】:

      您已将 selected key 设置为 nil -

      MyModel::CATEGORIES, # nil #, "Please Select"

      尝试将您的代码更改为:

      = f.select :category,grouped_options_for_select(MyModel::CATEGORIES, :country, "Please Select")
      

      【讨论】:

      • 那没有任何区别
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多