In Rails 8.1, how does an Active Record model work with a composite primary key such as [:account_no, :invoice_no], and what changes for find and id?
answer
- supported since Rails 7.1
- read from the schema or primary_key = [...]
- find takes an array, arrays of arrays
- id returns an array
- to_param joins with an underscore
basics
~20 sSince Rails 7.1 Active Record reads a composite key from the table, or takes self.primary_key = [:account_no, :invoice_no]; find then takes an array of values, id returns an array, and to_param joins the parts with an underscore.
solid answer
~40 sComposite primary keys are supported since Rails 7.1, and I assume 8.1. If the table declares `PRIMARY KEY (account_no, invoice_no)`, Active Record reads it and `Invoice.primary_key` is `["account_no", "invoice_no"]`; otherwise set `self.primary_key = [:account_no, :invoice_no]`. `Invoice.find(["A-10442", 118])` returns one record and `find([[...], [...]])` several. `invoice.id` returns `["A-10442", 118]`, `id=` expects an array, and `reload`, `update` and `destroy` put every key column in their `WHERE`. `first` and `last` order by all key columns. `to_param` joins the values with `_` (`A-10442_118`), and `params.extract_value(:id)` splits them again. Two traps: in `find_by(id:)` and `where(id:)`, `id` means an `id` column, never the composite key, and associations need array `foreign_key:` options.
code
ruby · 11 linesclass Invoice < ApplicationRecord
self.primary_key = [:account_no, :invoice_no]
has_many :invoice_lines, foreign_key: [:account_no, :invoice_no]
end
invoice = Invoice.find(["A-10442", 118])
invoice.id # => ["A-10442", 118]
invoice.to_param # => "A-10442_118"
# InvoicesController#show
Invoice.find(params.extract_value(:id)) # "A-10442_118" -> ["A-10442", "118"]go deeper
Recall that a table can have a key of several columns and that Active Record supports it in current Rails.
Explain how find, id and to_param change shape when the key is composite.
Spot the find_by(id:) and association traps, and check the underscore round trip before trusting URLs built from composite keys.
Decide whether a composite key reflects the domain or a legacy accident, weighing it against a surrogate id with a unique index.
## Why a composite key The utilities-billing database keys invoices by **account plus sequence**: invoice 118 of account `A-10442`. No single column identifies a row, so the table's primary key is `(account_no, invoice_no)`. Before Rails 7.1 Active Record supported only single-column keys, and teams reached for third-party gems. **Since 7.1** composite keys are built in; this answer assumes Rails 8.1. ## Declaring the key - **From the schema.** Active Record asks the database for the primary key. When it is composite, `Invoice.primary_key` returns an array such as `["account_no", "invoice_no"]` with no model code. - **In the model.** When the table declares no key, or for clarity: `self.primary_key = [:account_no, :invoice_no]`. - **In a migration.** `create_table :invoices, primary_key: [:account_no, :invoice_no]` creates such a table; the migration helpers belong to the migrations topic. ## What changes on the model | Call | Single key | Composite key | |---|---|---| | `Invoice.find(...)` | `find(118)` | `find(["A-10442", 118])` | | several records | `find([1, 2])` | `find([["A-10442", 118], ["A-10442", 119]])` | | `invoice.id` | `118` | `["A-10442", 118]` | | `invoice.id = ...` | a value | an array | | `invoice.to_param` | `"118"` | `"A-10442_118"` | | `first` / `last` order | by the key | by every key column | Under the hood: 1. `find` with one array builds `WHERE account_no = 'A-10442' AND invoice_no = 118`. 2. `reload`, `update` and `destroy` build the same multi-column `WHERE`. 3. `first` orders by `account_no, invoice_no` ascending; `last` reverses both. 4. `where` accepts a tuple form: `Invoice.where(Invoice.primary_key => [["A-10442", 118], ["B-2001", 4]])`. ## Routes, forms and params Active Record joins composite key values with an **underscore** in `to_param`, so `invoice_path(invoice)` builds `/invoices/A-10442_118` and `form_with model: @invoice` posts to it. In the controller, `params.extract_value(:id)` splits on `_` and returns `["A-10442", "118"]`, ready for `Invoice.find`. A key value that itself contains an underscore breaks this round trip, which is worth checking before adopting the scheme. ## The traps - **`:id` in conditions is a column, not the key.** In `find_by` and `where`, `id` refers to an `id` attribute, never to the full composite key. When the key is something like `[:shop_id, :id]`, `find_by(id: 5)` matches that one column across every shop. Look records up with `find` and the full array. - **Associations need explicit keys.** By default an association uses only the `id` part of a composite key, which works only when the key contains a unique `id` column. Give `belongs_to` and `has_many` array options: `has_many :invoice_lines, foreign_key: [:account_no, :invoice_no]`. - **Cost.** The guide's own advice: composite keys add complexity and can be slower than a single key column, so use one when the data really requires it (a legacy schema, sharding or multitenancy), not by default. ## A version note On Rails 7.0 or older none of this exists: `primary_key=` with an array is not supported and `find` takes single values. Upgrading a legacy app to 7.1 or later is often what makes dropping a composite-key gem possible. ## Composite key or surrogate id? The same uniqueness can usually be expressed two ways, and interviewers like to hear the trade-off: | | Composite primary key | Surrogate `id` plus unique index | |---|---|---| | Matches a legacy schema as is | yes | needs a new column and backfill | | `find`, `id`, URLs | arrays and `A-10442_118` params | one value, plain routes | | Associations | array `foreign_key:` on both sides | Rails defaults work | | Gems and admin tools | must understand array keys | often assume a single `id` | | Uniqueness guarantee | the key itself | the unique index | For a table the app owns outright, a surrogate `id` with a unique index on `(account_no, invoice_no)` is usually simpler. For a schema shared with other systems, or one sharded by account, the composite key avoids rewriting data, and Rails 7.1 and later handles it natively.
- An Order model has primary key [:shop_id, :id]. Why can Order.find_by(id: 5) return another shop's order?In `find_by` and `where`, `id` refers to the `id` column, not the composite primary key. The query matches `id = 5` alone, so it can return the first order numbered 5 from any shop. `Order.find([shop_id, 5])` uses the whole key.
- How does a controller turn /invoices/A-10442_118 back into a key Invoice.find accepts?`params.extract_value(:id)` splits the parameter on the `_` delimiter that Active Record's `to_param` used and returns `["A-10442", "118"]`, which `Invoice.find` accepts as one composite key.
- Saying Rails 8.1 still needs a third-party gem for composite primary keys.
- Passing two arguments, find("A-10442", 118), expecting one record by composite key.
- Using find_by(id:) to look up a record by its whole composite key.
- Expecting has_many to infer both key columns without an array foreign_key:.
- Assuming to_param joins composite key values with a slash.
Assumes Rails 8.1; composite primary keys have been built into Active Record since Rails 7.1, and earlier versions support single-column keys only.