Using a duration field in a Rails model

前端 未结 4 1346
温柔的废话
温柔的废话 2021-01-30 07:00

I\'m looking for the best way to use a duration field in a Rails model. I would like the format to be HH:MM:SS (ex: 01:30:23). The database in use is sqlite locally and Postgr

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-30 07:56

    I tried using ActiveSupport::Duration but had trouble getting the output to be clear.

    You may like ruby-duration, an immutable type that represents some amount of time with accuracy in seconds. It has lots of tests and a Mongoid model field type.

    I wanted to also easily parse human duration strings so I went with Chronic Duration. Here's an example of adding it to a model that has a time_spent in seconds field.

    class Completion < ActiveRecord::Base
      belongs_to :task
      belongs_to :user
    
      def time_spent_text
        ChronicDuration.output time_spent
      end
    
      def time_spent_text= text
        self.time_spent = ChronicDuration.parse text
        logger.debug "time_spent: '#{self.time_spent_text}' for text '#{text}'"
      end
    
    end
    

提交回复
热议问题