I have an ActiveRecord model Event
with a datetime column starts_at
. I would like to present a form, where date and time for starts_at
are chosen separately (e.g. "23-10-2010"
for date and "18:00"
for time). These fields should be backed by the single column starts_at
, and validations should preferably be against starts_at
, too.
I can of course muck around with virtual attributes and hooks, but I would like a more elegant solution. I have experimented with both composed_of
(rdoc), and attribute-decorator (lighthouse discussion, github) without success.
Below is a rough outline of what I would like..
class Event < ActiveRecord::Base validates_presence_of :start_date end # View # On submission this should set start_date. form_for @event do |f| f.text_field :starts_at_date # date-part of start_date f.text_field :starts_at_time_of_day # time-of-day-part of start_date f.submit end
Any help appreciated.
Do you have to have a text_field
in the view?
As far as I can tell, you can have a date_time
field and then just use two different input fields to set the different parts of the field.
form_for @event do |f| f.date_select :starts_at f.time_select :starts_at, :ignore_date => true f.submit end
Since the rails date and time select helpers set five different parameters (starts_at(1i)
for the year part, 2i
for the month part, and so on), that means that the date_select
only sets them for the date part, while if you pass :ignore_date => true
to the time_select
, it will only set the hour and minute part.
If you must have a text_field
I'm not sure how to do it, but it might be possible to do using some jQuery magic before setting the datetime parameters before sending the form.
Was looking at this today for a Rails project, and came across this gem:
https://github.com/shekibobo/time_splitter
Setting DateTimes can be a difficult or ugly thing, especially through a web form. Finding a good DatePicker or TimePicker is easy, but getting them to work on both can be difficult. TimeSplitter automatically generates accessors for date, time, hour, and min on your datetime or time attributes, making it trivial to use different form inputs to set different parts of a datetime field.
Looks like it would do the job for you
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