Skip to content

Instantly share code, notes, and snippets.

@croby
Last active December 11, 2015 02:49
Show Gist options
  • Save croby/4533461 to your computer and use it in GitHub Desktop.
Save croby/4533461 to your computer and use it in GitHub Desktop.
Changing a non-primary-key column to a Rails-standard `id` primary key column, and back down again
def up
rename_column :table_name, :old_id_col, :id
change_column :table_name, :id, :primary_key
end
def down
rename_column :table_name, :id, :old_id_col
change_column :table_name, :old_id_col, :integer, :null => true
remove_column :table_name, :id
end
@croby
Copy link
Author

croby commented Jan 14, 2013

Given a table with no primary key set, change the name of the column, then set that column as the primary key. Tricky part here is migrating down, where we have to rename the column to be the old column name, change that column to be an int with :null => true, then remove the id column, because for some reason the rename column isn't removing that ID column

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment