Skip to content

Instantly share code, notes, and snippets.

@dnch
Created April 16, 2013 02:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dnch/5392985 to your computer and use it in GitHub Desktop.
Save dnch/5392985 to your computer and use it in GitHub Desktop.
# app/models/foo.rb
# Keep in mind, this doesn't even factor in TimeZones.
class Foo
# Including this line gives your model two virtual
# attributes - `date` and `time` - which you can use as
# methods in your form_for / f.text_field calls, etc
attr_writer :date, :time
# returns the date component of starts_at, to ensure
# that your `date` field is pre-populated when using
# form_for.
def date
starts_at.strftime("%Y-%m-%d")
end
# returns the time component of starts_at
def time
starts_at.strftime("%H:%M")
end
# This ensures that the values in your virtual fields
# are coalesced into your actual database field
before_save :save_date_and_time
private
def save_date_and_time
# replace with whatever logic you need to ensure that
# date and time are in the correct format. All you really need
# is to ensure that the value you pass to starts_at
# matches YYYY-MM-DD HH:MM:SS.
starts_at = date + time
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment