multiparameter error with datetime_select

后端 未结 6 734
傲寒
傲寒 2021-01-02 09:13

I have the following code in my form.

<%= f.datetime_select(:date_time, :prompt => {:day => \'Day\', :month => \'Month\', :year => \'Year\'},          


        
6条回答
  •  轮回少年
    2021-01-02 09:48

    I had the same problem using a date dropdown that wasn't backed by a database attribute. I wrote a little Rack middleware to cope with the problem:

    class DateParamsParser
      def initialize(app)
        @app = app
      end
    
      def call(env)
        if %w{POST PUT}.include? env['REQUEST_METHOD']
          params = Rack::Utils.parse_query(env["rack.input"].read, "&")
    
          # selects only relevant params like 'date1(1i)'
          filtered_params = params.select{ |key, value| key =~ /\(\di\)/ }
          # delete date params
          filtered_params.each { |key, value| params.delete(key) }
    
          # returns something like {'date1' => [2012, 5, 14], 'date2' => [2002, 3, 28]}
          date_array_params = filtered_params.sort.reduce({}) do |array_params, keyvalue|
            date_key = keyvalue.first.match(/(.+)\(/)[1] + ']'
            array_params[date_key] ||= []
            array_params[date_key] << keyvalue.last
            array_params
          end
    
          # Creates params with date strings like {'date1' => '2012-5-14', 'date2' => '2002-3-28'}
          date_params = Hash[date_array_params.map{ |key, date_array| [key, date_array.join('-')] }]
    
          params.merge! date_params
          env["rack.input"] = StringIO.new(Rack::Utils.build_query(params))
          env["rack.input"].rewind
        end
    
        @app.call(env)
      end
    end
    

    And in application.rb I put

    config.middleware.insert_before ActionDispatch::ParamsParser, "DateParamsParser"
    

    Note that I only build a date string here. So if you also require time you'll need to build the date_params differently.

提交回复
热议问题