How to rename a column and change its type by migration same time

后端 未结 4 1431
迷失自我
迷失自我 2021-02-06 23:43

In my general_exams table, I have a column named semester, type is string. Now I want to change its name to semester_id, type

相关标签:
4条回答
  • 2021-02-07 00:06

    This error is because there is existing data in the tables (or default values, perhaps ..) that PG doesn't know how to convert from string to integer. Either get rid of the data or tell PG how you want to convert it, using PG specific SQL (I think you'll want USING) and execute migration command. See Rails guides on migrations.

    0 讨论(0)
  • 2021-02-07 00:12

    Your problem is probably that the semester contains data that cannot be converted to integers. That's why you get a cast error.

    I suspect you need to do more work to make this work as the only thing that comes to mind is removing the column and creating a new one with the correct values.

    But you can simply remove_column and then add_column in one migration. That should work flawlessly.

    I'd also suggest you only add_column first, then do the mapping process where you map the old semester value onto the new semester_id and then drop the column.

    Keep in mind that you can do ActiveRecord manipulations inside your migration. So you can put that code in there.

    0 讨论(0)
  • 2021-02-07 00:16

    I hope this help

    class ModifyColumnTables 
      def change
        remove_column :posts, :old_column
        add_column :posts, :new_column, :type_of_column
      end
    end
    
    0 讨论(0)
  • 2021-02-07 00:20

    This works as of Rails 4

    def change
      rename_column :general_exams, :semester, :semester_id
      change_column :general_exams, :semester_id, :integer
    end
    
    0 讨论(0)
提交回复
热议问题