使用db:migrate编辑数据库字段类型

时间:2011-01-19 15:06:20

标签: datetime ruby-on-rails-3 dbmigrate

我正在开发Ruby on Rails Web应用程序,我有兴趣更改Project模型中两个字段的类型。当我创建模型时,我给了我的两个字段(start_timeend_time)int类型,我想将其更改为日期/时间类型。

由于我正在与团队合作(也可能因为这样做是正确的)我想使用rake db:migrate更改这些字段类型。我如何创建一个文件来执行此操作? Ruby / Rails中存在的最佳(或唯一)日期/时间类型是什么?

1 个答案:

答案 0 :(得分:1)

运行script/rails generate migration UpdateTimeFields并使用以下内容。 (还有一个change_column方法,但我不相信它能够将int列更改为datetime列,同时仍保留任何数据。)

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