Rails:使用现有数据更改现有列的数据类型的影响 [英] Rails: Effects of changing the data type of an existing column with existing data

查看:97
本文介绍了Rails:使用现有数据更改现有列的数据类型的影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能会在错误的地方提出这个问题,所以请轻松点,并指出正确的方向。

I could be asking this in the wrong place so go easy and point me in the right direction if I am.

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

I can't get my head around how changing the data type of an existing column in an existing table with existing data in Rails will effect any app I am working on.

如果我有一个名为<$的布尔列c $ c>足球。 足球可以为true或false。我有足球还是没有。我意识到,例如 ,有时可以借用足球。因此,我想将圆柱足球的数据类型更改为字符串。字符串的值可以为true,false或借出的字符串。

If I have a boolean column called football. The football can be either true or false. Either, I have a football or I don't. I realise that, for example, the football can sometimes be loaned. So, I want to change the data type of the column football to be a string. The value of the string can be true, false or loaned.

为此运行迁移后,我要经历多长时间?我现有的数据将会怎样?我需要做些什么来减轻对所有现有数据的混乱?而且,我是否在正确的地方问这个问题?

How bad a time am I going to have after running the migration for this? What will happen to my existing data? What do I need to do to mitigate against messing up all my existing data? And, am I asking this question in the right place?

推荐答案

如果我是我,那么可以通过创建一个新列来做到这一点,然后更新旧列中的所有内容,然后删除旧列,然后重命名新列。另外,我也不会将布尔值另存为 true或 false(如果您只是更改类型,那么Rails应该默认提供给您)...如果是我,我会创建一个枚举

If I were you I would do this by creating a new column, then updating everything from the old column, and then removing the old column, and renaming the new one. Also I wouldn't save a boolean as "true" or "false" either (which Rails should give you by default if you DO just change the type)... If I were you I would create an enum for this column.

首先进行迁移:

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

现在在模型中设置枚举:

Now set up the enum in your model:

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

这篇关于Rails:使用现有数据更改现有列的数据类型的影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆