How to get a Date from date_select or select_date in Rails?

后端 未结 7 1186
小鲜肉
小鲜肉 2020-11-30 04:05

Using select_date gives me back a params[:my_date] with year, month and day attributes. How do get a Date ob

相关标签:
7条回答
  • 2020-11-30 04:40

    Here is another one for rails 5:

    module Convert
      extend ActiveSupport::Concern
    
      included  do
        before_action :convert_date
      end
    
      protected
    
      def convert_date
        self.params = ActionController::Parameters.new(build_date(params.to_unsafe_h))
      end
    
      def build_date(params)
        return params.map{|e| build_date(e)} if  params.is_a? Array
    
        return params unless params.is_a? Hash
    
        params.reduce({}) do |hash, (key, value)|
          if result = (/(.*)\(\di\)\z/).match(key)
            params_name = result[1]
            date_params = (1..3).map do |index|
              params.delete("#{params_name}(#{index}i)").to_i
            end
            hash[params_name] =  Date.civil(*date_params)
          else
            hash[key] = build_date(value)
          end
    
          hash
        end
      end
    end
    

    You need to include it to your controller or application_controller.rb:

    class ApplicationController < ActionController::Base
      include Convert
    end
    
    0 讨论(0)
提交回复
热议问题