格式化月份和年份下拉红宝石

时间:2016-07-28 06:43:05

标签: ruby-on-rails ruby ruby-on-rails-4

我试图在其中填充年份和月份的下拉列表。

代码正在运行但有一些限制。我无法在月份字段中添加0并且无法获取年份字段的最后2个数字。

此外,选择月份并允许所需的空白也不起作用。

月份代码:

 <%= select_month nil, {add_month_numbers_true: true}, {name: nil, id: 
"month_num", :required => true, :include_blank => "Select Month"} %>

输出:

<select include_blank="Select Month" required="required" id="month_num">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>

以上需要在选项值方面添加01, 02, 03,而不是1, 2, 3...

年份代码:

<%= select_year nil, {start_year: Date.today.year, end_year: 
Date.today.year+10}, {name: nil, id: "year_num", :required => true,
 :include_blank => "Select Year"} %>

输出:

<select include_blank="Select Year" required="required" id="year_num">
<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>
</select>

以上需要在选项值方面添加16, 17, 18,而不是2016, 2017, 2018...

3 个答案:

答案 0 :(得分:2)

这将按预期工作

<%= select_tag "month", options_for_select((1..12).map {|m| [Date::MONTHNAMES[m], format('%02d', m)]}), :required => true, :include_blank => "Select Month" %>  
<%= select_tag "year", options_for_select((Date.today.year..(Date.today.year + 10)).map {|m| [m, m % 100]}), :required => true, :include_blank => "Select Year" %>

答案 1 :(得分:1)

select_monthselect_year不接受value代码的自定义<option>

一种选择是将select_tagoptions_for_select一起使用。

# <select> tag for month names
<%= select_tag :month_num, options_for_select(Date::MONTHNAMES.compact.each_with_index.map{ |month, index| [month, '%02d' % (index + 1)] }) %>


# <select> tag for years
<%= select_tag :year_num, options_for_select((Date.today.year..(Date.today + 10.years).year).map{ |year| [year, '%02d' % (year % 100)] }, '%02d' % (Date.today.year % 100)) %>

答案 2 :(得分:0)

试试这个

<%= select_year nil, {start_year: Date.today.strftime("%y").to_i, end_year: (Date.today+10.years).strftime("%y").to_i}, {name: nil, id: "year_num", :required => true, :include_blank => "Select Year"} %>