Last Updated: February 25, 2016
·
5.037K
· rwz

Using UUID instead of ids with Postgres and Rails

Postgres is quite awesome and can do a lot of stuff. For example it can generate UUIDs for you. It also is capable of using these generated UUIDs instead of plain old integer ids.

This is how Rails migrations would look like if want to do something similar:

class EnableUuid < ActiveRecord::Migration
  def up
    execute 'CREATE EXTENSION "uuid-ossp";'
  end

  def down
    execute 'DROP EXTENSION "uuid-ossp";'
  end
end

and then

class CreateEntries < ActiveRecord::Migration
  def up
    execute 'CREATE TABLE entries (id uuid PRIMARY KEY DEFAULT uuid_generate_v4());'
    change_table :entries do |t|
      t.string :name, null: false
      t.timestamps
    end
  end

  def down
    drop_table :entries
  end
end

4 Responses
Add your response

In Rails 4 uuid is a built-in type for postgres. So it would look like this:

class AddGuuidToSites < ActiveRecord::Migration
  def self.up
    add_column :sites, :guuid, :uuid
    add_index :sites, :guuid
  end

  def self.down
    remove_column :sites, :guuid
  end
end
over 1 year ago ·

@dpsk you can get the same thing in rails 3 using postgres_ext gem. The main point of this protip is how to make uuid column

  • primary key
  • autogenerated
over 1 year ago ·

@rwz Sorry, didn't pay attention that you are using uuid as primary key, good stuff :)

over 1 year ago ·

Ugh. Bloat your primary key from an INT to a long string, making indexes much bigger, comparisons take longer. This might make sense if you are sharding and don't have a real primary key, but I can't think of any other reason to do it.

over 1 year ago ·