Rails: UUID as default database ID with Postgres

A 1 minute read, Posted by Thomas Brennetot on Tue, Aug 20, 2019
Tags rails, ror, 5.2, uuid, postgres, setup

In a recent project using Doorkeeper (OAuth2 gem), it was a lot better to use UUID as primary key: - cleaner for an API to not expose incremental IDs - adding an uuid field will force to do extra SQL query and requires more custom code

Here what’s you need to to

To generate uuid by default.

# config/initializers/generators.rb

Rails.application.config.generators do |g|
  g.orm :active_record, primary_key_type: :uuid

You gonna need to have the a database plugin setup:

# rails generate migration enable_uuid_extension
class EnableUuidExtension < ActiveRecord::Migration[5.2]
  def change
    enable_extension  'pgcrypto' # Don't use 'uuid-ossp'

An example from Doorkeeper migration (-> type: :uuid).

# db/migration/...
create_table :oauth_access_tokens, id: :uuid, default: -> { "gen_random_uuid()" } do |t|
  t.references :resource_owner, index: true, type: :uuid
  t.references :application, type: :uuid

The Rails guide for the UUID: https://edgeguides.rubyonrails.org/active_record_postgresql.html#uuid