skip to content

In Rails YAML fixtures, how do label references and ActiveRecord::FixtureSet.identify fill foreign keys for belongs_to, polymorphic and has_many :through rows?

level: middleimportance: should knowfreq 45%

answer

  1. the label hashes to a stable id
  2. team: riverside instead of team_id
  3. polymorphic: label (Type)
  4. inline list writes the join rows
  5. an explicit id breaks label refs

basics

~20 s

Rails derives each row's id from its label with ActiveRecord::FixtureSet.identify, so team: riverside becomes team_id = identify(:riverside); polymorphic refs add (Type), and has_many :through or HABTM lists like matches: opening_day, derby write the join rows.

solid answer

~40 s

When a fixture has no `id`, Rails sets it to `ActiveRecord::FixtureSet.identify(label)`: a CRC32 hash of the label below 2^30, or a version 5 UUID for UUID keys. The same label always produces the same id, so another file can refer to the row by label. For a `belongs_to`, write the association name and a label, `team: riverside`, and Rails writes `team_id`. For a polymorphic `belongs_to`, add the type in brackets, `sponsorable: riverside (Team)`, which also fills `sponsorable_type`. For `has_and_belongs_to_many` or `has_many :through`, a comma list on one side, `matches: opening_day, derby`, makes Rails insert the join-table rows itself. The trap: if a row sets an explicit `id: 1`, references to its label still compute the hash, so they point at a row that does not exist.

code

yaml · 17 lines
yaml
# test/fixtures/matches.yml
opening_day:
  home_team: riverside
  away_team: harbor_city
  kickoff_at: 2026-08-15 15:00:00
  status: scheduled

# test/fixtures/players.yml
alice:
  name: Alice Moreau
  team: riverside
  email: [email protected]
  matches: opening_day

# test/fixtures/sponsorships.yml
kit_deal:
  sponsorable: riverside (Team)

go deeper

for a junior

Know that you write team: riverside instead of a team_id, and that ids come from the labels.

for a middle

Explain identify's deterministic hash, the (Type) syntax for polymorphic refs, and how inline lists fill join tables.

for a senior

Diagnose dangling references from mixed explicit ids, use the foreign-key verification on load, and know when a join fixture file is required.

for a principal

Set conventions for a large fixture graph, such as no explicit ids and join files for rich joins, so references stay readable as the schema grows.

## Labels become ids Every fixture row has a **label**, its top-level YAML key. If the row does not set its primary key, Rails generates one from the label just before inserting: - **integer keys:** `ActiveRecord::FixtureSet.identify(:riverside)` returns `Zlib.crc32("riverside") % (2**30 - 1)`, a stable number below 2^30; - **UUID keys:** `identify(:riverside, :uuid)` returns a version 5 UUID derived from the label; - **composite keys:** `ActiveRecord::FixtureSet.composite_identify(label, Model.primary_key)` returns one value per key column. Because the same label always yields the same id, on every machine and every run, any file can point at a row without knowing a number. ## belongs_to by label Write the **association name**, not the foreign-key column: ```yaml # test/fixtures/players.yml alice: name: Alice Moreau team: riverside # becomes team_id: identify(:riverside) position: forward # enum label, resolved to its stored value ``` Rails reflects on the model's `belongs_to :team`, removes the `team` key and writes `team_id`. Writing `team_id: 1` instead still works, but then you have to know the id. ## Polymorphic belongs_to For `belongs_to :sponsorable, polymorphic: true`, Rails cannot guess the target table, so the type goes in brackets after the label: ```yaml # test/fixtures/sponsorships.yml kit_deal: sponsorable: riverside (Team) boot_deal: sponsorable: alice (Player) ``` That fills `sponsorable_id` with the hashed label and `sponsorable_type` with `Team` or `Player`. ## Join tables without a join file Both `has_and_belongs_to_many` and `has_many :through` accept an inline list on one side: ```yaml alice: team: riverside matches: opening_day, derby # Player has_many :matches, through: :appearances ``` Rails inserts one row per target into the join table (`appearances` here) with both foreign keys and, for a join model, its timestamps. Two limits: 1. Only the two keys and timestamps are written. If the join table has another `NOT NULL` column without a default, such as `minutes_played`, the insert fails; write an `appearances.yml` file instead. 2. Put the list on **one** side only, or the rows are inserted twice. ## $LABEL and ERB - `$LABEL` inside a string value is replaced with the row's label: `email: [email protected]` gives `[email protected]`. - ERB runs before the YAML is parsed, so an old-style join file can call the hash directly: `player_id: <%= ActiveRecord::FixtureSet.identify(:alice) %>`. ## The explicit-id trap | What you wrote | What a reference to `riverside` resolves to | Result | |---|---|---| | no `id` on `riverside` | `identify(:riverside)` | matches | | `id: 1` on `riverside` | `identify(:riverside)`, not 1 | dangling foreign key | | `team_id: 1` on the player | 1 | matches only because both sides hard-code it | With `verify_foreign_keys_for_fixtures` on (the default since `load_defaults` 7.0) and real foreign-key constraints, a dangling reference fails the load. The message is "Foreign key violations found in your fixture data. Ensure you aren't referring to labels that don't exist on associations." Without constraints, it surfaces later as a `nil` association. The rule: either give no row an explicit id, or use ids everywhere for that table. ## Summary - Leave `id` out and let labels generate it. - Reference by association name and label: `team: riverside`. - Add `(Type)` for polymorphic targets. - Use inline lists for simple join tables, and a join fixture file when the join row has data of its own. ## Composite primary keys For tables with composite primary keys, a row without values for the key columns gets them from `composite_identify(label, Model.primary_key)`, which derives one value per column from the label's hash. A `belongs_to` whose `foreign_key:` is an array is resolved the same way, so label references keep working. Hand-written join files need the matching sub-key, read with `composite_identify(:label, Model.primary_key)[:id]` inside ERB. ## Reading a dangling reference When the load fails with the foreign-key message, the cause is nearly always one of three things: 1. a typo in a label (`team: riversdie`); 2. a target row that sets an explicit `id`; 3. a reference to a fixture file the test class does not load, when it declares `fixtures :players` instead of `fixtures :all`.

  • Why does a Rails fixture reference work across files without any load order?
    Rails never looks the referenced row up. It computes the foreign key with `ActiveRecord::FixtureSet.identify(label)`, which is deterministic. All fixture tables are inserted with referential integrity disabled and checked afterwards, so the order of the files does not matter.
  • When should you write a join fixture file instead of an inline list in Rails fixtures?
    When the join row carries data of its own, such as `minutes_played` on an appearance, or needs its own label to be referenced elsewhere. The inline list writes only the two foreign keys and timestamps, so extra NOT NULL columns would fail the insert.

Labels work like seat names on a stadium plan: every copy of the plan computes the same seat number from the name, so any file can say 'Riverside's seat' without anyone writing the number down. Writing a number by hand on one seat breaks every reference that computes it from the name.

  • Rails looks up the referenced team in the database when loading team: riverside.
  • Fixture ids are assigned in file order, starting from 1.
  • A polymorphic reference needs separate _id and _type keys in every fixture.
  • Setting id: 1 on a fixture keeps label references to it working.
  • Inline has_many :through lists can fill extra columns on the join rows.