3

I need to change the id of the existing model to uuid. I'm using this guide:

http://rny.io/rails/postgresql/2013/07/27/use-uuids-in-rails-4-with-postgresql.html

But no idea how to adapt the migration below to changing (not creating a new one):

 class CreateDocuments < ActiveRecord::Migration
  def change
   create_table :documents, id: :uuid  do |t|
      t.string :title
      t.string :author
      t.timestamps
    end
  end
end
electrify
  • 155
  • 1
  • 10
  • See the [reference](http://blog.arkency.com/2014/10/how-to-start-using-uuid-in-activerecord-with-postgresql/) document – Prashant4224 Oct 29 '15 at 10:56
  • According to your guide , you need to put enable_uuid_ossp_extension migration at first place in your migration list, you need to rename it . this works for me when i try it on my machine . – Pardeep Saini Oct 29 '15 at 11:15

2 Answers2

5

Try This.

    class documents < ActiveRecord::Migration
  def change
    add_column :documents, :uuid, :uuid, default: "uuid_generate_v4()", null: false

    change_table :documents do |t|
      t.remove :id
      t.rename :uuid, :id
    end
    execute "ALTER TABLE documents ADD PRIMARY KEY (id);"
  end
end

source

Community
  • 1
  • 1
1

Rails automatically handles uuid, so you just need to change id to uuid, set the column type (uuid for PGSQL, string for MYSQL) and repopulate the table with the new uuid.

In doing this myself, I've only ever changed the id column to uuid for Rails to populate it automatically.

$ rails g migration ChangeID

#db/migrate/change_id______.rb
class ChangeId < ActiveRecord::Migration
   def change
      rename_column :documents, :id, :uuid
      change_column :documents, :uuid, :uuid #-> will only work for PGQL, will have to make it string for MYSQL
   end
end

$ rake db:migrate

This will rename your :id column to uuid, assigning the respective column type to it.

And, yes, I've used :uuid before...

enter image description here

--

A good ref:

Richard Peck
  • 76,116
  • 9
  • 93
  • 147
  • I got this error after following your answer, https://gist.github.com/anonymous/186d053b87fec30fc4218692267e7dee. can you help me out – gates Aug 12 '16 at 08:50
  • This answer is kind of out of date now, I'll leave a comment with updated code – Richard Peck Aug 12 '16 at 14:33