Search code examples
ruby-on-railsrubypostgresqlmigrationruby-on-rails-5

Rails: From UUID to ID


I've created a model Order with UUID as the primary key. Now, I'd like to change it back to a normal incremental integer.

I've tried to run a migration like:

add_column :orders, :id, :primary_key

But it obviously doesn't work because there is already an id column.

I've found many posts on how to go from id to uuid, but not how to reverse it.


Solution

  • Does the table have data?

    If no, just drop old id column and add new:

    remove_column :orders, :id
    add_column :orders, :id, :primary_key
    

    If yes, rename id column to id_deprecated

    rename_column :orders, :id, :id_deprecated
    add_column :orders, :id, :primary_key
    

    and add your logic to handle references of old_id in other tables.