Created
April 16, 2013 02:51
-
-
Save dnch/5392985 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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