Rails:使用现有数据更改现有列的数据类型的效果

我可能会在错误的地方问这个问题,所以如果我是这样的话,请轻松指出我正确的方向。

我无法理解如何使用Rails中的现有数据更改现有表中现有列的数据类型将影响我正在处理的任何应用程序。

如果我有一个名为football的布尔列。 football可以是真的也可以是假的。 或者,我有足球,或者我没有足球。 我意识到, 例如 ,足球有时可以借出。 所以,我想将列football的数据类型更改为字符串。 字符串的值可以是true,false或loaned。

在为此运行迁移后,我将有多糟糕的时间? 我现有的数据会怎样? 我需要做些什么来减少搞乱我现有的所有数据? 而且,我在正确的地方问这个问题吗?

如果在rails中将列类型从布尔值更改为字符串,则不必担心,因为现有数据将自动更改为字符串。 就像你有布尔值true一样,这将自动转换为字符串“true”。

仅供参考,我在我的系统上检查过这个;)

如果我是你,我会通过创建一个新列,然后更新旧列中的所有内容,然后删除旧列,并重命名新列来完成此操作。 另外我也不会将布尔值保存为“true”或“false”(如果你只是改变类型,Rails应该默认给你)…如果我是你,我会为这个列创建一个枚举 。

首先你的迁移:

 class ChangeFootball < ActiveRecord::Migration def change # Add the new column. Use an integer type, so you can set up an Enum in your model add_column :examples, :football_new, :integer, default: 0 # Set up the new column values for all your existing records: Example.where(football: true).update_all football_new: 0 Example.where(football: false).update_all football_new: 1 # Now remove the old column: remove_column :examples, :football # Finally, rename the new column to the same as the old one rename_column :examples, :football_new, :football # Oh, and add an index: add_index :examples, :football end end 

现在在模型中设置枚举:

 enum football: { own: 0, lost: 1, misplaced: 2, loaned: 3 }