慣性聚合 高效追讀感興趣之博客、新聞、科技資訊
閱原文 以慣性聚合開啟

推薦訂閱源

小众软件
小众软件
博客园 - 叶小钗
有赞技术团队
有赞技术团队
大猫的无限游戏
大猫的无限游戏
博客园_首页
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
L
LangChain Blog
Hugging Face - Blog
Hugging Face - Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
aimingoo的专栏
aimingoo的专栏
Blog — PlanetScale
Blog — PlanetScale
爱范儿
爱范儿
T
Tailwind CSS Blog
Jina AI
Jina AI
量子位
Stack Overflow Blog
Stack Overflow Blog
人人都是产品经理
人人都是产品经理
J
Java Code Geeks
V
Visual Studio 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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python)
善主键之道:Rails开发者 ULID 指南
Zil Norvilis · 2026-05-28 · via DEV Community

尝于前文论及雪片之标识,其善也,然需稍事配置,盖因须理"工作者之标识"也。

若欲求简而易行,而得同等之利——安全之URL与迅捷之数据库排序——则当察ULIDs(通用唯一且可字顺排序之标识)。

何不径用UUID乎?

众开发者多弃自增之整数,而择UUID者,盖欲隐其商贾之量也。若君之订单号order/550e8400-e29b...如是,则无人知君有客一,抑或百万。

然UUID有大弊:其全然无序,不可预测也。
将数百万随机UUID插入数据库,则"树索引"渐次崩坏,迟滞难行。尔之数据库必须遍寻硬盘,方得新数据安插之所。

ULID可解此弊。
ULID乃128位(与UUID同),然其首部乃为时戳。此乃ULID之序时也。其独异若UUID,然其序若整数。

今示以四步之法,使ULID行于汝之Rails 8应用。

第一步:安设宝石

吾将用ulid宝石以生字符串。于汝之Gemfile中加此:

gem "ulid"

Enter fullscreen mode Exit fullscreen mode

于终端中运行bundle install

第二步:ULID之虑

吾欲使添加ULID于任一模型之事极为便捷。此举之良策,乃以Concern为之。此码将确保每创一新记录,必生一ULID而赋之ID。

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

步入全屏模式 退出全屏模式

第三步:迁跃

新模之造,须告Rails,其idstring,且当禁其本有之自增之理.

rails g model Product name:string

步入全屏模式 退出全屏模式

启迁移之文,如斯修之:

# 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

入全屏之状 出全屏之状

步四:更化其模

今,但纳吾于步二所书之虑。

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

入全屏之状 出全屏之状

步五:观其效验

启尔 Rails 之台(bin/rails c(JHSNS_SEG_b35e528b_49__)并创制数物:

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

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

全屏模式 退出全屏模式

细察之,诸ID皆以同文始,盖同分创也。既可序,犹可运Product.order(:id),自当列于时序之正!

言我何以好ULIDs于Rails

  1. 性能更优:盖因ID可排序,故PostgreSQL(或SQLite)可将其附于索引之末。此法较随机UUID,于"重写"之应用为快。
  2. 易读:ULID所用字母表特殊(Crockford's Base32),去易淆之字如"I"、"L"、"O",故用户若须键入,较易辨识。
  3. 无需设置: 与 Snowflake IDs 不同,尔无需配置服务器 ID 或工作节点。尔但安装此宝石,即可行矣。

大抵如是。此乃微调架构,使尔之应用更显专业,且更具可扩展之能。