如何获得在我的 Rails 表单中呈现的第一个选项?

How do I get a first option to render in my Rails form?

我正在使用 Rails 4.2.3。我想从人们可以 select 状态创建一个 select 菜单,我希望它有一个“Select 状态”选项作为第一个选项。所以,在我看来我把

<%= select_tag :state, options_for_select(us_states, {:prompt => 'Select State'}) %>

然而,呈现的是状态列表,而不是“Select状态”选项。这是呈现的 HTML …

<select name="state" id="state"><option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="DC">District of Columbia</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
…
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option></select>

我还需要做什么才能获得第一个渲染选项?

options_for_select 助手没有 :prompt 选项,您可以在文档中查看:

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_for_select

相反,我只是将提示明确添加到您的状态列表中:

<%= select_tag :state, options_for_select([["Select State", nil], *us_states]) %>

结果:

<select name="state" id="state">
  <option value="">Select State</option>
  <option value="AL">Alabama</option>
  <option value="AK">Alaska</option>
  ...
</select>

这应该有效:

<%= select_tag :state, options_for_select(us_states), {:prompt => 'Select State'} %>