skip to content

Seed Data

db/seeds.rb loads reference and demo rows through bin/rails db:seed, written with find_or_create_by! so reruns stay safe. Interviewers ask when seeds, data migrations or one-off tasks fit.

part ofRuby on Railsread it →
on this pageshow

explore

questions

5

In Rails, what is db/seeds.rb for, how do you load it, and why write it with find_or_create_by! instead of create!?

level: juniorimportance: must knowfreq 55%

answer

  1. plain Ruby run against the current database
  2. bin/rails db:seed
  3. aborts while migrations are pending
  4. safe to run twice
  5. block runs only when creating

basics

~20 s

db/seeds.rb is a Ruby file that creates the rows an app needs, such as countries and default plans, and bin/rails db:seed runs it. It may run many times, so find_or_create_by! makes reruns find existing rows instead of duplicating them.

solid answer

~40 s

`db/seeds.rb` is plain Ruby that runs with the app loaded, so it uses your models: `Country.find_or_create_by!(code: "PT") { |c| c.name = "Portugal" }`. `bin/rails db:seed` runs it against the current environment's database (after refusing if migrations are pending), and `db:setup` and `db:reset` run it after loading the schema. The generated file says it should be **idempotent**, because it gets run again: after a teammate pulls new seeds, in CI, on a fresh database. `create!` would insert duplicates or fail on a unique index the second time. `find_or_create_by!` looks the row up by the hash and creates it only if missing; the block sets extra attributes only on create, and the bang raises `ActiveRecord::RecordInvalid` instead of silently returning an unsaved record. To change attributes of rows that already exist, find them and call `update!`.

code

ruby · 9 lines
ruby
# db/seeds.rb
{ "PT" => "Portugal", "JP" => "Japan", "BR" => "Brazil" }.each do |code, name|
  Country.find_or_create_by!(code: code) { |c| c.name = name }
end

Plan.find_or_create_by!(code: "free") do |plan|
  plan.name = "Free"
  plan.monthly_price_cents = 0
end

go deeper

for a junior

Know where seeds live, that bin/rails db:seed runs them, and that find_or_create_by! keeps a second run from duplicating rows.

for a middle

Explain what find_or_create_by! does step by step: lookup by the hash, block only on create, RecordInvalid on bad data, and why existing rows are not updated.

for a senior

Design seeds that converge: stable unique keys, explicit updates for changing attributes, reference data first, and demo data kept out of production.

for a principal

Decide what belongs in seeds at all versus migrations or admin tooling, and how reference data changes reach every environment.

## What the seeds file is Every Rails app gets **`db/seeds.rb`**. It is ordinary Ruby that runs with the whole application loaded, so it can use models, validations and callbacks. Its job is to put in the rows the application needs to be usable: **reference data** such as the list of countries a language-learning app supports and its default subscription plans, and, in development, some **demo data** such as sample learners. The generated file opens with the rule that matters most: > This file should ensure the existence of records required to run the application in every environment (production, development, test). The code here should be idempotent so that it can be executed at any point in every environment. ## How it gets loaded | Command | What it does with seeds | |---|---| | `bin/rails db:seed` | runs `db/seeds.rb` against the current environment's database | | `bin/rails db:setup` | creates the database, loads the schema, then seeds | | `bin/rails db:reset` | drops the database, then does what `db:setup` does | | `bin/rails db:seed:replant` | truncates the tables, then seeds | `db:seed` first checks for **pending migrations** and aborts with a list of them and the instruction to run `bin/rails db:migrate`, because seeding against an out-of-date schema would fail halfway. Under the hood the task calls `Rails.application.load_seed`, which `load`s the file inside the app's reloader. ## Why idempotency, and how find_or_create_by! gives it Seeds are not run once. They run when a new developer sets up, when someone adds a country and teammates pull, in CI, and against brand-new databases. A seeds file written with `create!` works the first time and then either **duplicates** every row or crashes on a unique index. `find_or_create_by!` is the standard fix: ```ruby Country.find_or_create_by!(code: "PT") do |country| country.name = "Portugal" end ``` 1. The **hash** is the lookup key: Rails runs `find_by(code: "PT")`. 2. If a row exists, it is returned and **the block does not run**. 3. If not, Rails creates the record with the hash attributes, passing it to the block first so you can set the rest. 4. The **bang** means a failed validation raises `ActiveRecord::RecordInvalid`. The non-bang `find_or_create_by` would return an unsaved record and the seed run would carry on, leaving a gap nobody notices. In Rails 8.1, if the insert hits a unique index because another process created the same row in between, `find_or_create_by!` catches `ActiveRecord::RecordNotUnique` and looks the row up again. That only helps when the lookup columns have a **unique index**, which reference tables should have anyway. ## The trap: changes to rows that already exist Because the block runs only on create, editing it does nothing to existing rows: - changing the Pro plan's price from 999 to 1199 cents in the block leaves every database that already has the plan at 999; - putting the price in the hash instead makes the lookup miss and **creates a second Pro plan**. Keep the lookup on a stable natural key and write the changeable attributes explicitly when they must converge: ```ruby plan = Plan.find_or_initialize_by(code: "pro") plan.update!(name: "Pro", monthly_price_cents: 1199) ``` ## Seeds from engines An engine, such as a mounted billing or admin engine, can ship its own `db/seeds.rb`. Rails does not load it automatically: `bin/rails db:seed` loads only the application's file. If the engine's reference data is needed, call it from the app's seeds with `Billing::Engine.load_seed`, which loads the engine's file through the same `load_seed` method the application uses. Order it before the app's own rows if they depend on it. ## Habits for a good seeds file - Key every lookup on a column with a unique index (`code`, `slug`, an ISO code), not on `id` or a display name. - Seed reference data before data that points at it: countries and plans before learners. - Keep demo data out of production (see per-environment seeding). - Use the bang methods so a bad row stops the run loudly. - Prefer clear Ruby over cleverness; the file is read far more often than it changes.

  • Why not key the plan lookup on its name?
    Display names change. Rename "Pro" to "Pro Monthly" in the hash and the next run finds nothing and creates a second plan. Key on a stable code with a unique index, and set the name in the block or with `update!`.
  • What is the difference between find_or_create_by! and create_or_find_by!?
    `find_or_create_by!` selects first and inserts only when nothing is found. `create_or_find_by!` inserts first and, if a unique constraint rejects the row, finds the existing one. The second suits rows that are usually new; for seeds, where rows usually exist, selecting first avoids a failed insert on every run.

find_or_create_by! is like a hotel's guest check-in that first looks for an existing reservation under your booking code: if one exists you get that room, and a new room is assigned only when no reservation is found.

  • seeds run once, so create! is fine
  • editing the find_or_create_by! block updates existing rows
  • find_or_create_by without the bang is just as safe in seeds
  • db:seed runs pending migrations before seeding
  • seeds.rb is only for development data

Assumes Rails 8.1, where find_or_create_by! is find_by followed by create_or_find_by!, so a unique-index race ends in a second lookup instead of an error.

open as a page

In a Rails 8.1 app, how do you seed demo learners only in development while countries and plans load in every environment, including production?

level: middleimportance: should knowfreq 35%

basics

~20 s

Rails loads the same db/seeds.rb in every environment, so the file must branch itself: reference data such as countries and plans at the top, demo learners behind Rails.env.development? or in a db/seeds/development.rb that seeds.rb loads only there.

open as a page

What does bin/rails db:seed:replant do in Rails 8.1, and what stops it from wiping a production database?

level: middleimportance: should knowfreq 25%

basics

~10 s

db:seed:replant empties every table of the current environment's databases, except Rails' own schema_migrations and ar_internal_metadata, and then runs db/seeds.rb. It is a protected task: against a database last used as production it raises ActiveRecord::ProtectedEnvironmentError.

open as a page

A Rails 8.1 release adds a Family plan that production must have; does it belong in db/seeds.rb, a data migration, or a one-off task?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Usually both: a deploy runs migrations, not seeds, so a data migration adds the plan to existing databases, and db/seeds.rb adds it to new ones, which since Rails 8.0 load the schema instead of replaying migrations.

open as a page

In a multi-database Rails 8.1 app, what does the seeds: key in config/database.yml control, and what is its default?

level: middleimportance: nice to knowfreq 12%

basics

~10 s

seeds: decides whether bin/rails db:prepare runs db/seeds.rb after it sets up that database. It defaults to true for the primary database and false for the others, such as the cache, queue and cable databases.

open as a page