Where is the Rails method that converts data from `datetime_select` into a DateTime object?

前端 未结 7 1797
醉酒成梦
醉酒成梦 2020-11-30 07:29

When I use <%= f.datetime_select :somedate %> in a form, it generates HTML like:


                        
    
提交评论

  • 2020-11-30 07:51

    Had to do something very similar, and ended up using this method:

    def time_value(hash, field)
      Time.zone.local(*(1..5).map { |i| hash["#{field}(#{i}i)"] })
    end
    
    time = time_value(params, 'start_time')
    

    See also: TimeZone.local

    0 讨论(0)
  • 2020-11-30 07:54

    Someone else here offered solution of using DateTime.new, but that won't work in Postgresql. That will save the record as is, that is, as it was inserted in form, and thus it won't save in database as utc time, if you are using "timestamp without timezone". I spent hours trying to figure out this one, and the solution was to use Time.new rather than DateTime.new:

    datetime = Time.new(params["fuel_date(1i)"].to_i, params["fuel_date(2i)"].to_i, 
                            params["fuel_date(3i)"].to_i, params["fuel_date(4i)"].to_i,
                            params["fuel_date(5i)"].to_i)
    
    0 讨论(0)
  • 2020-11-30 07:57

    The start of that code path, seems to be right about here:

    https://github.com/rails/rails/blob/d90b4e2/activerecord/lib/active_record/base.rb#L1811

    That was tricky to find! I hope this helps you find what you need

    0 讨论(0)
  • 2020-11-30 07:57

    I had this issue with Rails 4. It turned out I forgot to add the permitted params to my controller:

    def event_params
      params.require(:event).permit(....., :start_time, :end_time,...)
    end
    
    0 讨论(0)
  • 2020-11-30 07:58

    Hi I have added the following on the ApplicationController, and it does this conversion.

        #extract a datetime object from params, useful for receiving datetime_select attributes
        #out of any activemodel
        def parse_datetime_params params, label, utc_or_local = :local
          begin
            year   = params[(label.to_s + '(1i)').to_sym].to_i
            month  = params[(label.to_s + '(2i)').to_sym].to_i
            mday   = params[(label.to_s + '(3i)').to_sym].to_i
            hour   = (params[(label.to_s + '(4i)').to_sym] || 0).to_i
            minute = (params[(label.to_s + '(5i)').to_sym] || 0).to_i
            second = (params[(label.to_s + '(6i)').to_sym] || 0).to_i
    
            return DateTime.civil_from_format(utc_or_local,year,month,mday,hour,minute,second)
          rescue => e
            return nil
          end
        end
    
    0 讨论(0)
  • 提交回复
    热议问题