Separate date and time form fields in Rails

Viewed 26162

I have an ActiveRecord model Eventwith 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.

5 Answers

Elegant solution may provide date_time_attribute gem:

class MyModel < ActiveRecord::Base
  include DateTimeAttribute

  date_time_attribute :starts_at
end

It will allow you to set starts_at_date and starts_at_time separately:

form_for @event do |f|
  f.text_field :starts_at_date
  f.text_field :starts_at_time
  f.submit
end

# this will work too:
form_for @event do |f|
  f.date_select :starts_at_date
  f.time_select :starts_at_time, :ignore_date => true
  f.text_field  :starts_at_time_zone
  f.submit
end

# or
form_for @event do |f|
  f.date_select :starts_at_date
  f.text_field  :starts_at_time
  f.submit
end

It will also allow you to play with time zones, use Chronic etc.

Related