Back

Using uuid as a primary key

It can be useful sometimes to setup a database table with a primary key that isn't sequential.

This could be used if you don't want users being able to guess Primary Keys in the database from your web app.

Turns out Rails 5 allows you to specify the ID as a uuid, if you are using postgres. But you need to enable the pgcrypto extension first.

Enabling PgCrypto on Postgres

In a new migration you can enable the extension like so:

class EnableExtensions < ActiveRecord::Migration[5.2]
  def change
    enable_extension 'pgcrypto'
  end
end

Creating the table

This enables you to create a new table with a UUID as the primary key.

  create_table :file_references, id: :uuid do |t|
    t.string :content_type, null: false
    t.hstore :meta_data
    t.integer :size
    t.timestamps
  end

Some folks might tell you that UUIDs as a primary key may result in slower write speeds at scale. I don't have any evidence either way, however I didn't think it would matter with my specific use case because it's a small table.