惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
B
Blog
Jina AI
Jina AI
N
Netflix TechBlog - Medium
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园_首页
Hugging Face - Blog
Hugging Face - Blog
博客园 - 聂微东
美团技术团队
Google DeepMind News
Google DeepMind News
WordPress大学
WordPress大学
阮一峰的网络日志
阮一峰的网络日志
U
Unit 42
The Cloudflare Blog
V
V2EX
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
小众软件
小众软件
罗磊的独立博客
Microsoft Security Blog
Microsoft Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
I
InfoQ
GbyAI
GbyAI
腾讯CDC
MongoDB | Blog
MongoDB | Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
The Better Primary Key: A Guide to ULIDs for Rails Develo...
Zil Norvilis · 2026-05-28 · via DEV Community

In a previous article, I talked about Snowflake IDs. They are great, but they require a bit of configuration because you need to manage "Worker IDs."

If you want something simpler that gives you the same benefits - secure URLs and fast database sorting—you should look at ULIDs (Universally Unique Lexicographically Sortable Identifiers).

Why not just use UUIDs?

Most developers switch from auto-incrementing integers to UUIDs because they want to hide their business volume. If your order ID is order/550e8400-e29b..., no one knows if you have 1 customer or 1 million.

But UUIDs have a major problem: they are completely random.
When you insert millions of random UUIDs into a database, the "B-Tree" index gets fragmented and slow. Your database has to jump all over the hard drive to find where to put the new data.

ULIDs fix this.
A ULID is 128 bits (just like a UUID), but the first part of the ID is a timestamp. This means ULIDs are chronological. They are unique like a UUID, but they sort like an Integer.

Here is how to implement ULIDs in your Rails 8 app in 4 easy steps.

STEP 1: Install the Gem

We will use the ulid gem to generate the strings. Add this to your Gemfile:

gem "ulid"

Enter fullscreen mode Exit fullscreen mode

Run bundle install in your terminal.

STEP 2: The ULID Concern

We want to make it very easy to add ULIDs to any model. The best way to do this is with a Concern. This code will ensure that every time we create a new record, a ULID is generated and assigned to the ID.

Create a new file at app/models/concerns/has_ulid.rb:

# app/models/concerns/has_ulid.rb
module HasUlid
  extend ActiveSupport::Concern

  included do
    # Before we save to the DB, generate the ULID
    before_create :set_ulid
  end

  private

  def set_ulid
    # ULID.generate creates a string like: 01ARZ3NDEKTSV4RRFFQ69G5FAV
    self.id ||= ULID.generate
  end
end

Enter fullscreen mode Exit fullscreen mode

STEP 3: The Migration

When you create a new model, you need to tell Rails that the id is a string, and you must disable the default auto-increment logic.

rails g model Product name:string

Enter fullscreen mode Exit fullscreen mode

Open the migration file and modify it like this:

# db/migrate/XXXXXXXXXXXXXX_create_products.rb
class CreateProducts < ActiveRecord::Migration[8.0]
  def change
    # id: false stops the automatic integer ID
    create_table :products, id: false do |t|
      # We use string for ULID primary key
      t.string :id, primary_key: true
      t.string :name

      t.timestamps
    end
  end
end

Enter fullscreen mode Exit fullscreen mode

STEP 4: Update the Model

Now, just include the concern we wrote in Step 2.

# app/models/product.rb
class Product < ApplicationRecord
  include HasUlid
end

Enter fullscreen mode Exit fullscreen mode

STEP 5: See it in action

Open your Rails console (bin/rails c) and create a few products:

Product.create(name: "Laptop")
Product.create(name: "Monitor")
Product.create(name: "Keyboard")

# Check the IDs
Product.pluck(:id)
# => ["01HQV...", "01HQV...", "01HQV..."]

Enter fullscreen mode Exit fullscreen mode

If you look closely, the IDs all start with the same characters because they were created in the same minute. Because they are sortable, you can still run Product.order(:id) and they will be in the correct chronological order!

Why I like ULIDs for Rails

  1. Better Performance: Because the IDs are sortable, PostgreSQL (or SQLite) can append them to the end of the index. This is much faster for "Write-Heavy" apps than random UUIDs.
  2. Readability: ULIDs use a special alphabet (Crockford's Base32) that excludes confusing letters like "I", "L", and "O". This makes them easier to read if a user has to type one in.
  3. No Setup: Unlike Snowflake IDs, you don't need to configure server IDs or worker nodes. You just install the gem and go.

That's pretty much it. It’s a small architectural change that makes your app feel much more professional and scalable.