2011-01-19 65 views
0

我正在研究Ruby on Rails Web應用程序,我有興趣改變Project模型中兩個字段的類型。當我創建模型時,我給了我的兩個字段(start_timeend_time),類型爲int,我想將其更改爲日期/時間類型。使用db編輯數據庫字段類型:migrate

由於我正在與一個團隊合作(也可能是因爲這樣做是正確的),所以我想用rake db:migrate更改這些字段類型。我將如何創建一個文件來做到這一點?什麼是Ruby/Rails中最好(或唯一)的日期/時間類型?

回答

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 
+0

我是否使用日期時間獲得任何額外的「功能」,如日期時間選擇器或錯誤消息的錯誤格式? – Nayish 2011-01-19 15:28:28

相關問題