Rails - return an array of months for a select tag

前端 未结 10 2521
谎友^
谎友^ 2021-02-07 10:02

I\'m in an app that is on Rails 2.3.8, and need to return an array of month names and numbers to be plugged into an options_for_select statement. What I\'ve got so far is kind

相关标签:
10条回答
  • 2021-02-07 10:08

    Try this!

    @months = [['-', '']]
    (1..12).each {|m| @months << [Date::MONTHNAMES[m], m]}
    
    0 讨论(0)
  • 2021-02-07 10:09

    Try it

    <% (1..12).each do |month|%>
      <%= link_to t('date.month_names')[month], '#' %>
    <% end %>
    
    0 讨论(0)
  • 2021-02-07 10:16

    Here's a sexy way to get the months only if that's all you want:

    Date::MONTHNAMES.slice(1..-1).map(&:to_sym)
    
    0 讨论(0)
  • 2021-02-07 10:20

    If you want it to be translated to the selected language.

    t("date.month_names")
    
    0 讨论(0)
  • 2021-02-07 10:25
    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]]
    

    Abbreviated selection with default option

    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]]
    
    0 讨论(0)
  • 2021-02-07 10:25

    You can use rails helper select_month, like:

    select_month(Date.today)
    
    0 讨论(0)
提交回复
热议问题