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
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
dncrht over 8 years ago
This website uses short-lived cookies to improve usability.
Accept or learn more