Rails migrations - change_column with type conversion

后端 未结 4 1434
深忆病人
深忆病人 2020-12-04 17:36

I already google\'d aroung a little bit and seems there\'s no satisfying answer for my problem.

I have a table with column of type string. I\'d like to run following

4条回答
  •  旧巷少年郎
    2020-12-04 18:03

    If your strings in smoking column are already valid boolean values, the following statement will change the column type without losing data:

    change_column :users, :smoking, 'boolean USING CAST(smoking AS boolean)'
    

    Similarly, you can use this statement to cast columns to integer:

    change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'
    

    I am using Postgres. Not sure whether this solution works for other databases.

提交回复
热议问题