views:

15

answers:

1

I am interacting with a time duration in a rails form, currently it is a text box and the format requires MM:SS

I have the validator:

validates_format_of :time, :with => /^[0-9]?[0-9]{1}[:][0-9]{2}$/, :allow_nil => true, :allow_blank => true, :message => 'format must be MM:SS'

though I want to store this in the database as an integer(seconds) to make it easier to do reporting on that field.

I overwrote the accessors as:

 def time=(new_time)
   parts = new_time.split(':')
   write_attribute(:time, (parts[0].to_i * 60) + parts[1].to_i)
 end

 def time
   Time.at(read_attribute(:time).to_i).gmtime.strftime('%R:%S')
 end

but it ends up sending a validation error since the time attribute is just an integer after it gets set by the time= method.

How do store a duration value in the database in seconds but still enforce validation in a different format (MM:SS)?

A: 

I don't know if this is the best solution, but I believe you could use after_validation like the following:

after_validation :convert_time_to_integer

def convert_time_to_integer
   parts = self.split(':')
   write_attribute(:time, (parts[0].to_i * 60) + parts[1].to_i)
end
j.