0

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?

Nachshon Schwartz
  • 15,289
  • 20
  • 59
  • 98

1 Answers1

1

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
Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
  • Do i get any extra 'features' using datetime, like a datetime picker or at least error messages for wrong format? – Nachshon Schwartz Jan 19 '11 at 15:28
  • When it's a datetime field, you can do proper validations, easily query the database for specific time ranges, etc. For a datetime picker, that's a UI element in the view which is not directly related to the database fields. However, most date pickers will submit data which is compatible with a datetime field. – Dylan Markow Jan 19 '11 at 15:31