Ruby on Rails + Postgres + UUID keys

How to configure Ruby on Rails and Postgres to use UUIDs for primary keys

· 1 min read
Ruby on Rails + Postgres + UUID keys
Assumption : Rails v6+, Postgres v9.1+

Ideally you will implement this configuration before you've created any tables.

Create a migration :  rails g migration postgres_uuid

class postgres_uuid < ActiveRecord::Migration[6.0]
    def change
        enable_extension 'pgcrypto'

Migrate :  rails db:migrate

Configuration done.

Models and tables

Once you have UUIDs enabled remember to ensure you specify UUIDs when creating tables.

Example migration using UUIDs.

class CreateInvoices < ActiveRecord::Migration[6.0]

  def change
    create_table :invoices, id: :uuid do |t|

    	t.string :type
	t.string :name



If you use generators you can update your application config to ensure that generators run in the future use UUID for their primary keys.

Create a new file in your project:  config/initializers/generators.rb

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

Default Sort

One side efffect of using UUIDs as our primary keys is that the default sort order will be "broken" - in that .first and .last will be ordered on the random nature of UUID's.

To resolve this situation we need to notify ActiveRecord that the default sort order should be created_at.

Update /app/models/application_record.rb

class ApplicationRecord < ActiveRecord::Base

  self.abstract_class = true
  # Adjust default sort order
  self.implicit_order_column = :created_at


Related Articles

Ruby on Rails 6 securing app secrets
· 2 min read
HTML form with localised dates
· 2 min read