Change a column type from Date to DateTime during ROR migration

MysqlRuby on-RailsRubyRuby on-Rails-3Migration

Mysql Problem Overview


I need to change my column type from date to datetime for an app I am making. I don't care about the data as its still being developed.

How can I do this?

Mysql Solutions


Solution 1 - Mysql

First in your terminal:

rails g migration change_date_format_in_my_table

Then in your migration file:

For Rails >= 3.2:

class ChangeDateFormatInMyTable < ActiveRecord::Migration
  def up
    change_column :my_table, :my_column, :datetime
  end

  def down
    change_column :my_table, :my_column, :date
  end
end

Solution 2 - Mysql

Also, if you're using Rails 3 or newer you don't have to use the up and down methods. You can just use change:

class ChangeFormatInMyTable < ActiveRecord::Migration
  def change
    change_column :my_table, :my_column, :my_new_type
  end
end

Solution 3 - Mysql

In Rails 3.2 and Rails 4, Benjamin's popular answer has a slightly different syntax.

First in your terminal:

$ rails g migration change_date_format_in_my_table

Then in your migration file:

class ChangeDateFormatInMyTable < ActiveRecord::Migration
  def up
   change_column :my_table, :my_column, :datetime
  end

  def down
   change_column :my_table, :my_column, :date
  end
end

Solution 4 - Mysql

There's a change_column method, just execute it in your migration with datetime as a new type.

change_column(:my_table, :my_column, :my_new_type)

Solution 5 - Mysql

AFAIK, migrations are there to try to reshape data you care about (i.e. production) when making schema changes. So unless that's wrong, and since he did say he does not care about the data, why not just modify the column type in the original migration from date to datetime and re-run the migration? (Hope you've got tests:)).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjdogView Question on Stackoverflow
Solution 1 - MysqlapneadivingView Answer on Stackoverflow
Solution 2 - MysqlLee McAlillyView Answer on Stackoverflow
Solution 3 - MysqlThomas KlemmView Answer on Stackoverflow
Solution 4 - MysqlNikita RybakView Answer on Stackoverflow
Solution 5 - MysqlfakeleftView Answer on Stackoverflow