I have a calendar system in which the user enters date and time for an event in a seperate text_field. I store the date and time in one attribute (begin) in the Event model I have a hard time figuring out how to combine the date and time input and combine it into the begin attribute.
I preferably want to do this via a virtual attribute (:date
and :time
) so I can easily map my form against those virtual attributes without the need to do something in the controller.
Many thanks
You can make your own accessor methods for the date and time attributes like this:
def date
datetime.to_date
end
def date=(d)
original = datetime
self.datetime = DateTime.new(d.year, d.month, d.day,
original.hour, original.min, original.sec)
end
def time
datetime.to_time
end
def time=(t)
original = datetime
self.datetime = DateTime.new(original.year, original.month, original.day,
t.hour, t.min, t.sec)
end
You should use before_validation callback to combine data from two virtual attributes into one real attribute. For example, something like this:
before_validation(:on => :create) do
self.begin = date + time
end
Where date + time
will be your combining logic of the two values.
Then you should write some attr_accessor methods to get individual values if necessary. Which would do the split and return appropriate value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With