I'm trying to get a text field that my users can enter in something that is parsable by the Chronic gem. Here is my model file:
require 'chronic'
class Event < ActiveRecord::Base
belongs_to :user
validates_presence_of :e_time
before_validation :parse_date
def parse_date
self.e_time = Chronic.parse(self.e_time_before_type_cast) if self.e_time_before_type_cast
end
end
I think that it is being called because if I misspell something in parse_date, it complains that it doesn't exist. I've also tried before_save :parse_date, but that doesn't work either.
How could I get this to work?
Thanks
This kind of situation looks like a good candidate for using virtual attributes in your
Event
model to represent the natural language dates and times for the view's purpose while the real attribute is backed to the database. The general technique is described in this screencastSo you might have in your model:
And in your view:
If the parse fails, then
e_time
will remainnil
and your validation will stop the record being saved.