ruby-on-rails-4html-selectjquery-ui-selectmenu

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


I’m using Rails 4.2.3. I want to create a select menu from whcih people can select states, and I would like it to have a “Select State” option as the first option. So, in my view I put

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

However, what is rendered are the list of states, but not the “Select State” option. Here is the HTML that is rendered …

<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>

What else do I need to do to get the first option to render?


Solution

  • There is no :prompt option for the options_for_select helper, which you can see in the documentation:

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

    Instead, I would just add the prompt explicitly to your list of states:

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

    Result:

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