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
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.
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.
I hope this help
class ModifyColumnTables def change remove_column :posts, :old_column add_column :posts, :new_column, :type_of_column end end
This works as of Rails 4
def change
rename_column :general_exams, :semester, :semester_id
change_column :general_exams, :semester_id, :integer
end