0

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

由于我正在与一个团队合作(也可能是因为这样做是正确的)我想使用rake db:migrate. 我将如何创建一个文件来做到这一点?Ruby/Rails 中最好的(或唯一的)日期/时间类型是什么?

4

1 回答 1

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
于 2011-01-19T15:23:31.710 回答