Godzilla74 Godzilla74 - 1 year ago 203
Ruby Question

Rails select field default option

I'm trying to have my select fields pre-populate two select fields related to credit card expiration month/year, obviously I'm doing something wrong:

In this case, the fields should have 03 selected as the default month and 2026 as the default year.

<div class="form-group">
<%= label_tag "Card Expiration", nil, required: true, class: "control-label col-md-3 col-sm-3 col-xs-4" %>
<div class="col-md-2 col-sm-2 col-xs-6">
<%= select_tag :exp_month, options_for_select(Date::MONTHNAMES.compact.each_with_index.map { |name,i| ["#{i+1} - #{name}", i+1] }), include_blank: false, "data-stripe" => "exp-month", class: "form-control", selected: @card.exp_month %>
<div class="col-md-2 col-sm-2 col-xs-6">
<%= select_tag :exp_year, options_for_select((Date.today.year..(Date.today.year+10)).to_a), selected: @card.exp_year, include_blank: false, "data-stripe" => "exp-year", class: "form-control" %>

This is what the generated HTML looks like for month:

<select class="form-control" data-stripe="exp-month" id="exp_month" name="exp_month" selected="selected"><option value="1">1 - January</option>
<option value="2">2 - February</option>
<option value="3">3 - March</option>
<option value="4">4 - April</option>
<option value="5">5 - May</option>
<option value="6">6 - June</option>
<option value="7">7 - July</option>
<option value="8">8 - August</option>
<option value="9">9 - September</option>
<option value="10">10 - October</option>
<option value="11">11 - November</option>
<option value="12">12 - December</option>

This is what the generated HTML looks like for year:

<select class="form-control" data-stripe="exp-year" id="exp_year" name="exp_year" selected="selected"><option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
<option value="2022">2022</option>
<option value="2023">2023</option>
<option value="2024">2024</option>
<option value="2025">2025</option>
<option value="2026">2026</option>

I've also verified that
@card.exp_month = 1
@card.exp_year = 2026

Answer Source

Add the "default option" as the second arg:

<%= select_tag :exp_year, options_for_select((Date.today.year..(Date.today.year+10)).to_a, @card.exp_year), include_blank: false, "data-stripe" => "exp-year", class: "form-control" %>

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

options_for_select([ "VISA", "MasterCard" ], "MasterCard")
# => <option value="VISA">VISA</option>
# => <option selected="selected" value="MasterCard">MasterCard</option>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download