A work around that might help:
First create a migration doing:
rename_column :the_models, :time, :old_time
add_column :the_models, :time, :time
So now, the model will have a field called old_time
containing the original time data, and a new time
field having the correct field type.
As a result, the existing forms would seems like lost all the time data, but at least they are calling the_model.time
to get the result.
The real work around part:
class TheModel < ActiveRecord::Base
def time
read_attribute(:time) || Time.parse(read_attribute(:old_time))
end
end
So now the time value will be saved into the time
filed.
When time
is nil, it will try to get the time value from the old_time
and convert it to a time object.
There are two drawbacks:
- Time.parse("12:34") would give you something like:
2010-12-14 12:34:00 +0800
Because you gave it only the hr and min, other fields are not reliable.
- You have a nearly deprecated field called
old_time
in the database. So in the future, you may want to completely remove that field, after you have confidence that all old_time
values has been converted to the time
field.
One more note:
You should convert existing forms, for :time
field which probably using text_field.
The text_field may become showing something like 2010-12-14 12:34:00 +0800
.
If you really still want to use text_field, you could:
def time
t = read_attribute(:time)
t.nil? ? read_attribute(:old_time) : t.strftime("%H:%M")
end
def time=(val)
write_attribute(:time, Time.parse(val))
end