how to convert a hash value returned from a date_select in rails to a Date object?

前端 未结 5 1677
感动是毒
感动是毒 2020-12-18 00:50

I have a date_select in my view inside a form, however on submit the value returned is in a hash form like so:

{\"(1i)\"=>\"2010\", \"(2i)\"=>\"8\", \"         


        
5条回答
  •  情书的邮戳
    2020-12-18 01:35

    Here's a generic way to do it, which also supports partial dates/times and empty fields:

    def date_from_date_select_fields(params, name)
      parts = (1..6).map do |e|
        params["#{name}(#{e}i)"].to_i
      end
    
      # remove trailing zeros
      parts = parts.slice(0, parts.rindex{|e| e != 0}.to_i + 1)
      return nil if parts[0] == 0  # empty date fields set
    
      Date.new(*parts)
    end
    

    Example usage:

    # example input:
    #
    # params = {
    #   "user":
    #     "date_of_birth(1i)": "2010",
    #     "date_of_birth(2i)": "8",
    #     "date_of_birth(3i)": "16"
    #   }
    # }
    date_of_birth = date_from_date_select_fields(params[:user], 'date_of_birth')
    

提交回复
热议问题