In a Rails 8.1 app on PostgreSQL, how do you give tables UUID primary keys, and what else must change once you do?
answer
- create_table ... id: :uuid
- gen_random_uuid() is the default
- references need type: :uuid
- generator primary_key_type setting
- first and last need implicit_order_column
basics
~20 sUse create_table :sneakers, id: :uuid; the adapter defaults the key to gen_random_uuid(). Foreign keys must then be uuid too (t.references :sneaker, type: :uuid), and first/last need implicit_order_column because random UUIDs do not sort by age.
solid answer
~40 s`create_table :sneakers, id: :uuid` makes `id` a `uuid` column whose default is `gen_random_uuid()`, so PostgreSQL generates the key and Rails reads it back on insert. That function is built in from PostgreSQL 13; older servers need `enable_extension "pgcrypto"`. Three things follow. Every reference must match: `t.references :sneaker, type: :uuid`, or the bigint foreign-key column cannot point at a uuid key. Generators should know: `config.generators { |g| g.orm :active_record, primary_key_type: :uuid }` (or `--primary-key-type=uuid`) adds `id: :uuid` and `type: :uuid` for you. And ordering changes: `first` and `last` order by the primary key, which is random for v4 UUIDs, so set `self.implicit_order_column = "created_at"` on the model.
go deeper
Recall create_table with id: :uuid and that references then need type: :uuid.
Explain the gen_random_uuid() default, the generator primary_key_type option and implicit_order_column for first and last.
Plan UUID keys from the start, configure generators and engines, and weigh index size and insert locality.
Decide between integer, random UUID and time-ordered keys for the whole system, including URLs and data merges.
## Why teams choose UUID keys A sneaker marketplace exposes listing URLs, order numbers and seller pages. With integer keys, `/sneakers/1042` tells anyone how many listings exist and invites guessing the next one. A UUID key is not guessable in sequence, can be generated by a client before it reaches the server, and stays unique when data from several databases is merged. The price is a 16-byte key instead of 8 and random insert order. Which kind of key a database should use in general is a broader design topic; this answer is about what Rails does once you choose UUIDs. ## Creating the tables ```ruby class CreateSneakers < ActiveRecord::Migration[8.1] def change create_table :sneakers, id: :uuid do |t| t.string :name, null: false t.references :seller, type: :uuid, null: false, foreign_key: true t.timestamps end end end ``` The PostgreSQL adapter's `primary_key` definition fills in `default: "gen_random_uuid()"` whenever the type is `:uuid`, so the database generates the value and the adapter reads it back with `RETURNING "id"`. Pass `default: nil` only if your code will always assign the id itself, for example with `SecureRandom.uuid`. `gen_random_uuid()` is part of PostgreSQL from version 13. On an older server it comes from the `pgcrypto` extension, enabled in a migration with `enable_extension "pgcrypto"`, which issues `CREATE EXTENSION IF NOT EXISTS`. ## What else must change | Area | Change | What breaks without it | |---|---|---| | foreign keys | `t.references :seller, type: :uuid` | a `bigint` column cannot reference a `uuid` key, so adding the foreign key fails | | generators | `g.orm :active_record, primary_key_type: :uuid` | every generated migration creates bigint ids and bigint references | | default ordering | `self.implicit_order_column = "created_at"` | `first` and `last` return effectively random rows | | join tables and polymorphic types | `type: :uuid` on each reference | the same type mismatch, discovered later | The generator setting goes in `config/application.rb` (or an initializer): ```ruby config.generators do |g| g.orm :active_record, primary_key_type: :uuid end ``` With it, `bin/rails generate model Sneaker name:string seller:references` writes `create_table :sneakers, id: :uuid` and `t.references :seller, ..., type: :uuid`. For a single model, `--primary-key-type=uuid` does the same. Engines that bring their own tables need the same treatment: the Active Storage guide warns that apps with UUID keys must set this generator option before installing it, so its tables reference UUIDs. ## Working with UUID values in Ruby - The adapter's uuid type **normalises** accepted formats (braces, upper case, missing dashes) to the canonical lower-case form, and casts anything else to `nil`. A malformed id in a URL therefore ends in `ActiveRecord::RecordNotFound` from `find`, not in a database error. - **Fixtures** keep working: when the key is a uuid, `ActiveRecord::FixtureSet.identify` turns each label into a deterministic version 5 UUID, so `sellers(:alice)` and the references to it agree across runs. - **URLs get longer**, because `to_param` returns the full 36-character id. That is usually acceptable, and a separate slug column can serve readable URLs. ## Ordering and first/last Active Record's ordered finders (`first`, `last`, `first(5)`) sort by the **implicit order column**, the primary key unless you say otherwise. Random UUIDs have no relation to insertion time, so `Sneaker.last` is not the newest listing. Set it per model: ```ruby class Sneaker < ApplicationRecord self.implicit_order_column = "created_at" end ``` Records are still subsorted by the primary key so ties resolve deterministically; `["created_at", nil]` turns that subsort off. Put the setting in `ApplicationRecord` if every model uses UUIDs. ## Costs to mention - **Index locality.** Random keys spread inserts across the whole primary-key index; time-ordered UUIDs reduce that, and how they compare is a PostgreSQL topic in its own right. - **Size.** Every foreign key and index on a reference is twice the width of a `bigint`. - **Mixed schemas.** Converting an existing bigint table to UUID keys is a data migration across every referencing table, so decide early.
- Why does Sneaker.last return an arbitrary listing after switching to UUID keys, and how do you fix it in Rails?Ordered finders sort by the implicit order column, which defaults to the primary key. Random v4 UUIDs do not follow insertion order, so the "last" key is not the newest row. Set `self.implicit_order_column = "created_at"` on the model (or on `ApplicationRecord`), or always call `order(:created_at)` explicitly.
- What does the primary_key_type generator option change in generated migrations?With `g.orm :active_record, primary_key_type: :uuid`, the migration generator adds `id: :uuid` to `create_table` and `type: :uuid` to every `references` or `add_reference` it writes, so new tables and their foreign keys match. Without it, generators keep writing bigint keys and references.
- Adds id: :uuid but leaves t.references as bigint
- Expects Sneaker.last to return the newest row with random UUID keys
- Assumes Rails generates the UUID in Ruby before the INSERT
- Insists pgcrypto must be enabled on every PostgreSQL version
- Switches a populated bigint table to UUIDs as a one-line change