Ruby-on-rails rails erb 表单助手 options_for_select :selected
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19120706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
rails erb form helper options_for_select :selected
提问by Drew Harris
I have an edit form in erb.
我在 erb 中有一个编辑表单。
<%= form_for @animal do |f| %>
Within the code I have a select with options:
在代码中,我有一个带有选项的选择:
<%= f.select :gender, options_for_select([['Mare'], ['Stallion'], ['Gelding']], :selected => :gender) %>
However, the select is not showing the correct selected value. What could I be doing wrong? I can get it to work if I hardcode it but of course that is not a viable option.
但是,选择未显示正确的选定值。我可能做错了什么?如果我对它进行硬编码,我可以让它工作,但这当然不是一个可行的选择。
回答by kristinalim
In your code, your options_for_select()call sets the selected value to "gender" and does not attempt to use the value from your form object.
在您的代码中,您的options_for_select()调用将所选值设置为“性别”,并且不会尝试使用表单对象中的值。
Please see the docs for options_for_select()for usage examples.
options_for_select()有关使用示例,请参阅文档。
options_for_select(['Mare', 'Stallion', 'Gelding'], f.object.gender)
options_for_select(['Mare', 'Stallion', 'Gelding'], :selected => f.object.gender)
Alternatively, you can do this, which will already use the gender()value for your form object:
或者,您可以这样做,这将已经使用gender()表单对象的值:
<%= f.select :gender, ['Mare', 'Stallion', 'Gelding'] %>
回答by Hans Hauge
By the way, if you are using :include_blank => true, this will set your current selection to blank even though the form "knows" what is selected.
顺便说一句,如果您正在使用:include_blank => true,即使表单“知道”选择了什么,这也会将您当前的选择设置为空白。

