Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting time into a time column with Ruby on Rails

I have run with a problem which i believe is Active Records fault. I am parsing an XML file which contains jobs. This xml file contains nodes which indicate walltime in the time format 00:00:00. I also have a model which will accept these jobs. However, when the time is larger than an actual 24H time, Active record inserts it as NULL. Examples below:

INSERT INTO `jobs` (`jobid`, `walltime`) VALUES('71413', 'NULL')

INSERT INTO `jobs` (`jobid`, `walltime`) VALUES('71413', '15:24:10')

Any ideas? Thank you!

like image 884
jalagrange Avatar asked Jul 26 '10 09:07

jalagrange


1 Answers

The standard SQL time and datetime data types aren't intended to store a duration. Probably in agreement with those standards, ActiveRecord's time attribute assignment logic uses the time parsing rules of the native Ruby Time class to reject invalid time of day.

The way to store durations, as you intend, is either:

  1. Store the duration as an integer (e.g. "number of seconds"), or
  2. Store two (date)times, a start and an end, and use date arithmetic on them.
class Thing < ActiveRecord::Base
  ...
  def duration
    return start - end
  end

  def duration=(length)
    start = Time.now
    end = start + length
  end
  ...
end
like image 51
Andres Jaan Tack Avatar answered Oct 12 '22 04:10

Andres Jaan Tack