Search code examples
datetimeruby-on-rails-3dbmigrate

Editing Database field type using db:migrate


I am working on a Ruby on Rails web application and I am interested in changing the type of two of the fields in my Project model. When I created the Model I gave two of my fields (start_time and end_time) the type int and I would like to change it to a date/time type.

Since I am working with a team (and probably also because it is right to do it this way) I would like to change these field types using rake db:migrate. How would i create a file to do this? What are the best (or only) date/time types existing in Ruby/Rails?


Solution

  • Run script/rails generate migration UpdateTimeFields and use the following. (There is also a change_column method, but I don't believe it's capable of changing an int column to a datetime column while still preserving any data).

    class UpdateTimeFields < ActiveRecord::Migration
      def self.up
        rename_column :projects, :start_time, :old_start_time
        rename_column :projects, :end_time, :old_end_time
        add_column :projects, :start_time, :datetime
        add_column :projects, :end_time, :datetime
    
        # If applicable, insert code to iterate through your existing
        # records and update the new start_time and end_time fields
        # based on your int data.
    
        remove_column :projects, :old_start_time
        remove_column :projects, :old_end_time
      end
    
      def self.down
        # do the opposite of above: rename the datetime fields, create the int
        # fields again, migrate the data back into the int fields, and delete
        # the datetime fields.
      end
    end