Rails - return an array of months for a select tag

前端 未结 10 2501
谎友^
谎友^ 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:25

    This is my solution for you, in case you work with I18n-based projects, that requires multilingual features:

    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}
    

    Regards

    0 讨论(0)
  • 2021-02-07 10:26

    Found this nifty way to shift off the first nil but return a new collection of months. You cannot use shift on it since that would try to modify the frozen variable.

    Date::MONTHNAMES.drop(1)
    
    0 讨论(0)
  • 2021-02-07 10:28

    Working for ROR 4

    select_month(0 , prompt: 'Choose month')
    
    0 讨论(0)
  • 2021-02-07 10:29
    # alternative 1 
    Date::MONTHNAMES.compact.zip(1.upto(12)).to_h
    
    # alternative 2
    Date::MONTHNAMES.compact.zip([*1..12]).to_h
    

    Outputs:

    {"January"=>0, "February"=>1, "March"=>2, "April"=>3, "May"=>4, "June"=>5, "July"=>6, "August"=>7, "September"=>8, "October"=>9, "November"=>10, "December"=>11}

    Example:

    # using simple_form
    f.input :month, collection:  Date::MONTHNAMES.compact.zip(1.upto(12)).to_h
    
    0 讨论(0)
提交回复
热议问题