On an Active Record model with random UUID primary keys, why does first return an arbitrary-looking record, and how do implicit_order_column and Rails 8.1 change that?
answer
- first sorts by the primary key
- random UUIDs carry no time order
- self.implicit_order_column = "created_at"
- primary key appended as tiebreaker
- MissingRequiredOrderError under 8.1 defaults
basics
~20 sfirst and last sort by the primary key when no order is given, and random UUIDs do not follow creation time. Setting implicit_order_column = "created_at" makes them sort by that column, with the primary key appended as a tiebreaker.
solid answer
~40 sOrder-dependent finders (`first`, `last`, `second`...) add `ORDER BY <primary key>` when the relation has no order. With an integer id that approximates creation order, but random UUIDs sort arbitrarily, so `Restaurant.first` returns whichever UUID is smallest. `self.implicit_order_column = "created_at"` makes those finders sort by `created_at` and then `id` (ascending for `first`, descending for `last`); the primary key is appended so ties stay deterministic, and `["created_at", nil]` turns that subsort off. It only affects implicit sorting: an explicit `order` is untouched. In Rails 8.1, an unordered `first` on a model with **no** order columns at all (no primary key, `implicit_order_column` or `query_constraints`) is deprecated, and a new app's `load_defaults 8.1` makes it raise `ActiveRecord::MissingRequiredOrderError`.
code
ruby · 16 linesclass Restaurant < ApplicationRecord
# id is a random UUID
self.implicit_order_column = "created_at"
end
Restaurant.last
# ORDER BY created_at DESC, id DESC LIMIT 1
class RatingSnapshot < ApplicationRecord
# backed by a database view with no primary key
end
RatingSnapshot.first
# load_defaults 8.1 => ActiveRecord::MissingRequiredOrderError
RatingSnapshot.order(:taken_on).first # explicit order: finego deeper
Know that first and last sort by the primary key when no order is given, so with UUID keys they do not mean oldest and newest.
Explain implicit_order_column, the appended primary-key tiebreaker and the nil opt-out, and which finders it affects.
Audit UUID and keyless models before upgrading load_defaults to 8.1, add explicit orders on hot paths, and index the implicit order column.
Factor time-ordered access into the choice of primary key type and make explicit ordering a review rule, so implicit defaults never carry business meaning.
## Where the implicit order comes from `first`, `last`, `second` through `fifth`, `forty_two`, `second_to_last` and `third_to_last` are **order-dependent finders**. When the relation has no `order`, Active Record must choose one, and it uses the model's **order columns**: 1. `implicit_order_column`, if set (a column name or an array of them), 2. then the primary key, or the composite `query_constraints`, appended as a tiebreaker. `take`, `pick` and `sole` do not sort, so they are unaffected. ## Why UUID keys make first look random With an auto-incrementing integer key, `ORDER BY id` roughly follows insertion, so `Restaurant.first` feels like "the oldest" and `last` like "the newest". A random UUID (version 4) has no relation to time: ```ruby Restaurant.last # SELECT ... ORDER BY restaurants.id DESC LIMIT 1 # => the restaurant whose UUID happens to sort highest ``` The query is correct and deterministic, but it does not mean "most recent", and code written against integer ids (`Restaurant.last` in a console, a test that expects the newest record, a "recently added" widget using `last`) quietly breaks. ## implicit_order_column ```ruby class Restaurant < ApplicationRecord self.implicit_order_column = "created_at" end Restaurant.first # ORDER BY restaurants.created_at ASC, restaurants.id ASC LIMIT 1 Restaurant.last # ORDER BY restaurants.created_at DESC, restaurants.id DESC LIMIT 1 ``` What it does and does not change: | Situation | Effect | |---|---| | `first` / `last` on an unordered relation | sorts by `created_at`, then the primary key | | `reverse_order` on an unordered relation | sorts by the implicit order column and the primary key, descending | | relation with an explicit `order` | untouched | | `take`, `pick`, plain iteration | untouched (no implied order) | | `["created_at", nil]` | sorts by `created_at` only, without the primary-key subsort | The primary-key subsort exists because timestamps can tie (bulk inserts, one transaction); dropping it with `nil` makes sense only when the listed columns are unique by themselves and you want the query to match a specific index. ## The Rails 8.1 change Some models have **no** order columns at all: a table created with `id: false`, a database view, or a legacy table without a primary key. Before 8.1, an unordered `first` on such a model silently ran without `ORDER BY` and returned whatever row came back. In Rails 8.1: - that silent behaviour is **deprecated** and logs a deprecation warning; - `config.active_record.raise_on_missing_required_finder_order_columns = true`, which `load_defaults 8.1` sets for new apps, turns it into `ActiveRecord::MissingRequiredOrderError`; - the deprecation message and CHANGELOG say the option is meant to go away in Rails 8.2, leaving raising as the only behaviour; on 8.1 it is still a setting. Ordinary tables with an `id` are not affected. Upgraded apps that still run older `load_defaults` see the warning first. ## Checking an app before switching the default When an upgraded app moves to `load_defaults 8.1`, or flips the setting in `config/initializers/new_framework_defaults_8_1.rb`: 1. List the models whose `primary_key` is `nil` and that set no `implicit_order_column`; views and join tables built with `id: false` are the usual suspects. 2. Search the code and the logs for the deprecation warning about order-dependent finders on those models. 3. Give each one an `implicit_order_column`, or add an explicit `order` before every `first`, `last` or `second_to_last`. 4. Turn on `raise_on_missing_required_finder_order_columns` and run the test suite; any remaining call now fails loudly. ## Practical guidance - On UUID-keyed models, set `implicit_order_column` to a timestamp, or never rely on `first`/`last` without an explicit `order`. - Prefer an explicit `order(created_at: :desc).first` in application code; keep `implicit_order_column` as a safety net for consoles, tests and generic code. - Index the implicit order column if `first`/`last` run on hot paths. - For keyless views, add an `implicit_order_column` or always order explicitly before upgrading the defaults.
- Does implicit_order_column change the order of Restaurant.all in an index page?No. It only supplies an order to finders that need one, such as `first`, `last` and an unordered `reverse_order`. `Restaurant.all` and plain iteration still run without `ORDER BY`, so list pages need an explicit `order` of their own.
- Why does Rails append the primary key after implicit_order_column?Timestamps tie, for example rows from one bulk insert, and ties make `first` nondeterministic. Appending the primary key gives a total order. Setting `implicit_order_column = ["created_at", nil]` opts out when the listed columns are already unique and you want the query to use a matching index.
- implicit_order_column changes the order of every query on the model
- With UUID keys, Restaurant.last still returns the newest restaurant
- In Rails 8.1 every unordered first raises MissingRequiredOrderError
- take sorts by implicit_order_column like first does
- Setting implicit_order_column removes the primary key from the sort
Assumes Rails 8.1 with load_defaults 8.1, which sets raise_on_missing_required_finder_order_columns = true; older defaults only log a deprecation warning.