Rails – 返回select标签的月份数组

我在Rails 2.3.8上的应用程序中,需要返回一个月份名称和数字的数组,以插入到options_for_select语句中。 到目前为止我所做的是有点工作,但不是真的。 我这样做的原因是因为select语句需要一个提示,默认情况下你不能在2.3.8中给出options_for_select(至少据我所知)。

这是我到目前为止:

@months = [['-', '']] (1..12).each {|m| @months << [[Date::MONTHNAMES[m], m]]} 

所以我想要返回的是这样的选项:

 January February 

但是,相反,我得到:

 January1 February2 

我错过了什么?

试试这个!

 @months = [['-', '']] (1..12).each {|m| @months << [Date::MONTHNAMES[m], m]} 
 Date::MONTHNAMES.each_with_index.collect{|m, i| [m, i]} => [[nil, 0], ["January", 1], ["February", 2], ["March", 3], ["April", 4], ["May", 5], ["June", 6], ["July", 7], ["August", 8], ["September", 9], ["October", 10], ["November", 11], ["December", 12]] 

带默认选项的缩写选择

 Date::ABBR_MONTHNAMES.compact.each_with_index.collect{|m, i| [m, i+1]} .insert(0, ['Please Select', nil]) => [["Please Select", nil], ["Jan", 1], ["Feb", 2], ["Mar", 3], ["Apr", 4], ["May", 5], ["Jun", 6], ["Jul", 7], ["Aug", 8], ["Sep", 9], ["Oct", 10], ["Nov", 11], ["Dec", 12]] 

您可以使用rails helper select_month,如:

 select_month(Date.today) 

为ROR 4工作

 select_month(0 , prompt: 'Choose month') 

如果您希望将其翻译为所选语言。

 t("date.month_names") 

试试吧

 <% (1..12).each do |month|%> <%= link_to t('date.month_names')[month], '#' %> <% end %> 
 # alternative 1 Date::MONTHNAMES.compact.zip(1.upto(12)).to_h # alternative 2 Date::MONTHNAMES.compact.zip([*1..12]).to_h 

输出:

{“January”=> 0,“February”=> 1,“March”=> 2,“April”=> 3,“May”=> 4,“June”=> 5,“July”=> 6, “八月”=> 7,“九月”=> 8,“十月”=> 9,“十一月”=> 10,“十二月”=> 11}

例:

 # using simple_form f.input :month, collection: Date::MONTHNAMES.compact.zip(1.upto(12)).to_h 

如果您使用基于I18n的项目这是我的解决方案 ,需要多语言function:

 def month_array # Gets the first day of the year date = Date.today.beginning_of_year # Initialize the months array months = {} # Iterate through the 12 months of the year to get it's collect 12.times do |i| # from 0 to 11 # Get month name from current month number in a selected language (locale parameter) month_name = I18n.l(date + i.months, format: '%B', locale: :en).capitalize months[month_name] = i + 1 end return months end # => {"January"=>1, "February"=>2, "March"=>3, "April"=>4, "May"=>5, "June"=>6, "July"=>7, "August"=>8, "September"=>9, "October"=>10, "November"=>11, "December"=>12} 

问候