Posted almost 9 years ago. Visible to the public.

DateTimes are Dates, beware


datetime = date = datetime.to_date #or

will assert:

datetime.is_a? Date == true datetime.is_a? DateTime == true datetime.instance_of? Date == false datetime.instance_of? DateTime == true

In case you have a table and a model like:

create_table :event do |t| :day t.string :description end class Event < ActiveRecord::Base; end

And you say:

event = => '2013-03-22')

Rails will convert the supplied value for day to the type of the database field, a Date.

BUT, if you say:

event = => datetime)

Rails will not convert anything, and it will remain as a DateTime until it's persisted. Then the database will truncate the time information and will be saved as a date indeed.

Consider this if you have methods on your model that deal with dates, because if you provide a DateTime you could get unexpected results. You might force the type of the fields to Date upon assignment:

class Event < ActiveRecord::Base def day=(day) @day = day.to_date end end

Owner of this card:

Last edit:
over 6 years ago
by dncrht
Posted by dncrht to HouseTrip Deck
This website uses short-lived cookies to improve usability.
Accept or learn more