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
Add your response
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
·
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rails
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#