我有一个包含两个字段的表单,其中第二个字段取决于在第一个下拉列表中选择的内容,如果我在第一个下拉列表中选择“亚洲”,则在第二个下拉列表中将显示“日本”和“中国”作为选项。
.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']
}
这可行,但是当我进入编辑页面时,第二个下拉列表未预先存储值,我该怎么做?
@dax是正确的,但是您需要显式设置选定的值,而不仅仅是属性。从api
selected_key-一个等于标签之一的value属性的值,该标签将设置selected属性。注意:此值可能与多个选项匹配,因为您可能在多个组中具有相同的选项。然后每个将被选中=“选定”。
您的代码应为
= f.select :category, grouped_options_for_select(MyModel::CATEGORIES, f.object.category)
编辑
传递给的最后一个参数grouped_options_for_select
应select
改为传递给,并且应为prompt
orinclude_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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句