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
Written by Pavel Pravosud
Related protips
4 Responses
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
@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
@rwz Sorry, didn't pay attention that you are using uuid as primary key, good stuff :)
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.