我需要將string
字段轉換爲integer
並使用enum
來代替。 在不丟失數據的情況下做到這一點的最佳方式是什麼?Rails 4遷移將列數據類型從字符串更改爲整數並保留後備數據(postgres)
這是當前遷移:
class CreateSystems < ActiveRecord::Migration
def change
create_table :systems do |t|
t.string :operation
t.string :status
t.timestamps null: false
end
end
end
然後我改變,像這樣的字段類型:
class ChangeColumnsForSystems < ActiveRecord::Migration
def change
change_column :systems, :operation, :integer
change_column :systems, :status, :integer
end
end
和更新模型文件。
/app/models/system.rb
...
enum operation { start: 0, stop: 1 }
enum status { init: 0, working: 1, complete: 2 }
...
如何更新舊的數據?
這種遷移將損壞的所有數據,因爲當你調用一個字符串'.to_i',你總是會得到預期0 接下來的這段代碼會工作。然而這不是最好的解決方案 'sys.operation = System.operations [sys.operation_str]' – Pav31