Search code examples
mysqlruby-on-railsmigrationruby-on-rails-5mysql2

Rails Migration: Adding comment to column without changing type


I'm currently working on a task to add a large number of comments to the columns in a database. I currently am approaching it trying to use the change_column function like the code below; however I'm running into some errors and worried I could accidentally change some types when I actually want to leave them alone.

change_column :tablename, :id, :bigint, comment: "id"

This results in the following error when the column in question is a foreign key.:

Mysql2::Error: Cannot change column 'id': used in a foreign key constraint 'fk_rails_(8 character series of numbers and letters)' of table 'databasename.tablename'

I also tried the following approach,

change_column_comment :tablename, :id, comment:'ID'

it results in the following error:

change_column_comment(:tablename, :id, {:comment=>"ID"})

rails aborted! NotImplementedError: ActiveRecord::ConnectionAdapters::Mysql2Adapter does not support changing column comments


Solution

  • The foreign keys is still an issue, but I've managed to get a reasonable result by extracting the current data types and using them in the following statement structure for each column.

    connection.execute("ALTER TABLE `tablename` MODIFY `id` bigint(20) comment 'ID'")