Ruby-on-rails 如何在 Rails 下拉菜单中设置默认选定项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4880038/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:17:38  来源:igfitidea点击:

How do I set the default selected item in a Rails drop-down menu?

ruby-on-rails

提问by keybored

When creating a standard Rails dropdown menu how do you set which item in the list should be default?
I ask because in the past I've been just putting a nil entry as the first item in my list of values that are going into the drop-down, but when using {:include_blank => true} the blank entry is not the default selected item, the first item from the list is.

创建标准 Rails 下拉菜单时,如何设置列表中的哪个项目是默认的?
我问是因为过去我只是将一个 nil 条目作为进入下拉列表的值列表中的第一项,但是当使用 {:include_blank => true} 时,空白条目不是默认值选定的项目,列表中的第一个项目是。

回答by fl00r

You can use :selected

您可以使用 :selected

<%= f.select :title, ['1','2','3','4'], :selected => '3' %>

回答by Mirko

You have many options to populate <select>tag with <option>tags, one of them is options_for_select(container, selected = nil) which takes a selected param which should be the value of your <option>field you want to be selected by default.

您有许多选项可以<select><option>标签填充标签,其中之一是options_for_select(container, selected = nil)它采用选定的参数,该参数应该是<option>您希望默认选择的字段的值。