How Data Type Changes Affect Existing Data in Rails

datatypesrailstype conversion

I'm working on a Rails app and would like to change the datatype for an existing column. It's currently a DateTime type, and I want to change it to a Date type. I found a way to do this here, but in this case, the person was not worried about preexisting data.

Right now, I plan to generate a migration…

rails g migration change_my_column_in_my_talbe

…and make the following change:

class ChangeMyColumnInMyTable < ActiveRecord::Migration
  def change
    change_column :my_table, :my_column, :date
  end
end

My question is: will the existing data be converted to a Date type, or will I need to create a rake task to convert the values for all of my existing DateTime values?

I found a similar question in which the conversion was from Boolean to String, and it seemed like the change would be automatic for existing data. I just want to be sure before I jump into making this change.

I'm using Rails version 4.2.0 and MySQL version 5.6.27 Homebrew. Any advice on this issue would be greatly appreciated!

Best Answer

I was able to set up a way to test this, and the existing data did convert from DateTime to Date types! As explained here, when doing this with MySQL as the adapter, using change_table triggers the following SQL call:

ALTER TABLE table_name MODIFY COLUMN column_name DATE

Two helpful warnings (courtesy of @SacWebDeveloper):

  1. This is an irreversible change, so if anyone else is trying this and may need to reverse, be sure to use the reversible command or write out the up and down changes.
  2. When converting from DateTime to Date, be aware that rounding uses fractions of a second. Example: '1999-12-31 23:59:59.499' => '1999-12-31', but '1999-12-31 23:59:59.500' => '2000-01-01'.