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:Two helpful warnings (courtesy of @SacWebDeveloper):
reversible
command or write out theup
anddown
changes.