Bird
Raised Fist0
Ruby on Railsframework~10 mins

Seed data in Ruby on Rails - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Seed data
Write seed data in db/seeds.rb
↓
Run rails db:seed command
↓
Rails loads seeds.rb file
↓
Execute seed commands
↓
Data inserted into database
↓
Seed data available for app use
Seed data is written in a file and run by a command to fill the database with initial data.
Execution Sample
Ruby on Rails
User.create(name: "Alice", email: "alice@example.com")
Product.create(name: "Book", price: 9.99)
Order.create(user_id: 1, product_id: 1)
This code adds initial users, products, and orders to the database when run.
Execution Table
StepActionCode ExecutedDatabase ChangeOutput/Result
1Create UserUser.create(name: "Alice", email: "alice@example.com")User table: 1 new recordUser Alice added
2Create ProductProduct.create(name: "Book", price: 9.99)Product table: 1 new recordProduct Book added
3Create OrderOrder.create(user_id: 1, product_id: 1)Order table: 1 new recordOrder linked to User 1 and Product 1
4EndNo more commandsNo changeSeeding complete
💡 All seed commands executed, database populated with initial data
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
User count01111
Product count00111
Order count00011
Key Moments - 2 Insights
Why does the order creation use user_id and product_id instead of user and product objects?
Seed files often use IDs directly because the related records must exist first; see execution_table step 3 where user_id: 1 and product_id: 1 link to existing records.
What happens if you run rails db:seed multiple times?
Running seeds multiple times can create duplicate records unless you add checks; the execution_table shows each create adds a new record every time.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the database change after step 2?
AOne new user record added
BOne new order record added
COne new product record added
DNo change
💡 Hint
Check the 'Database Change' column in row for step 2
At which step does the order get linked to the user and product?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the 'Code Executed' and 'Output/Result' columns for step 3
If you add a new product in seeds.rb before creating orders, how would the variable tracker change?
AUser count increases after order creation
BProduct count increases earlier, before order creation
COrder count increases before product count
DNo change in counts
💡 Hint
Refer to the 'Product count' row in variable_tracker and think about order of creation
Concept Snapshot
Seed data in Rails:
- Write initial data in db/seeds.rb
- Use create methods to add records
- Run with rails db:seed
- Data populates database tables
- Useful for setup and testing
Full Transcript
Seed data in Rails means writing code in the seeds.rb file to add initial records to the database. When you run the command rails db:seed, Rails loads and runs this file. Each create command adds a new record to the database tables. For example, creating a user, then a product, then an order linking them. The execution table shows each step adding data. Variables like user count increase as records are added. Beginners often wonder why IDs are used to link records; this is because related records must exist first. Running seeds multiple times can add duplicates unless handled. This visual trace helps understand how seed data fills the database step-by-step.

Practice

(1/5)
1. What is the main purpose of seed data in a Rails application?
easy
A. To run the Rails server
B. To create database tables automatically
C. To generate user interface templates
D. To fill the database with initial example data for testing and development

Solution

  1. Step 1: Understand what seed data is

    Seed data is used to add example or default data into the database to help developers test and develop features easily.
  2. Step 2: Identify the correct purpose

    Among the options, only filling the database with initial example data matches the purpose of seed data.
  3. Final Answer:

    To fill the database with initial example data for testing and development -> Option D
  4. Quick Check:

    Seed data purpose = Fill database with example data [OK]
Hint: Seed data = example info in database for testing [OK]
Common Mistakes:
  • Confusing seed data with database schema creation
  • Thinking seed data runs the server
  • Assuming seed data generates UI templates
2. Which command correctly runs the seed file to load data into the database in Rails?
easy
A. rails generate seed
B. bin/rails db:seed
C. bin/rails db:create
D. rails server

Solution

  1. Step 1: Recall the command to run seed data

    The standard command to load seed data in Rails is bin/rails db:seed.
  2. Step 2: Check other options

    rails generate seed is not a valid command, bin/rails db:create creates the database, and rails server starts the server.
  3. Final Answer:

    bin/rails db:seed -> Option B
  4. Quick Check:

    Run seed file = bin/rails db:seed [OK]
Hint: Run seeds with bin/rails db:seed command [OK]
Common Mistakes:
  • Using rails generate seed instead of db:seed
  • Confusing db:create with db:seed
  • Trying to run seeds with rails server
3. Given this seed code in db/seeds.rb:
3.times do |i|
  User.create(name: "User #{i + 1}")
end
What will be the names of the users created after running bin/rails db:seed?
medium
A. ["User 1", "User 2"]
B. ["User 0", "User 1", "User 2"]
C. ["User 1", "User 2", "User 3"]
D. ["User 3", "User 2", "User 1"]

Solution

  1. Step 1: Understand the loop and index

    The loop runs 3 times with i values 0, 1, 2.
  2. Step 2: Calculate user names

    Each user name is "User " plus i + 1, so names are "User 1", "User 2", "User 3".
  3. Final Answer:

    ["User 1", "User 2", "User 3"] -> Option C
  4. Quick Check:

    Loop 3 times with i+1 = User 1, 2, 3 [OK]
Hint: Remember loop index starts at 0, add 1 for names [OK]
Common Mistakes:
  • Using i without adding 1, causing off-by-one names
  • Assuming loop runs 2 times instead of 3
  • Mixing order of names
4. What is wrong with this seed code snippet?
User.create(name: "Alice")
User.create(name: "Bob")
User.create(name: )
medium
A. Missing value for name in the last User.create call
B. User.create cannot be called multiple times
C. Names must be unique, so this will fail
D. The code should be inside a loop

Solution

  1. Step 1: Check syntax of each User.create call

    The first two calls have valid name values. The last call has name: with no value, which is a syntax error.
  2. Step 2: Verify other options

    Calling User.create multiple times is allowed. Names do not have to be unique unless validated. Loop is optional.
  3. Final Answer:

    Missing value for name in the last User.create call -> Option A
  4. Quick Check:

    Empty value after name: causes syntax error [OK]
Hint: Check for missing values after keys in hashes [OK]
Common Mistakes:
  • Thinking multiple create calls are invalid
  • Assuming uniqueness is required by default
  • Believing loops are mandatory for seeds
5. You want to seed your database with categories but only if they don't already exist. Which seed code snippet correctly does this?
hard
A. ['Books', 'Movies', 'Music'].each do |name| Category.find_or_create_by(name: name) end
B. ['Books', 'Movies', 'Music'].each do |name| Category.create(name: name) end
C. Category.delete_all ['Books', 'Movies', 'Music'].each do |name| Category.create(name: name) end
D. Category.create(['Books', 'Movies', 'Music'])

Solution

  1. Step 1: Understand the requirement to avoid duplicates

    We want to add categories only if they don't exist yet, so we must check before creating.
  2. Step 2: Analyze each option

    ['Books', 'Movies', 'Music'].each do |name| Category.create(name: name) end always creates new records, causing duplicates. ['Books', 'Movies', 'Music'].each do |name| Category.find_or_create_by(name: name) end uses find_or_create_by which checks existence before creating. Category.delete_all ['Books', 'Movies', 'Music'].each do |name| Category.create(name: name) end deletes all categories first, which is destructive. Category.create(['Books', 'Movies', 'Music']) tries to create with an array directly, which is invalid syntax.
  3. Final Answer:

    ['Books', 'Movies', 'Music'].each do |name| Category.find_or_create_by(name: name) end -> Option A
  4. Quick Check:

    Use find_or_create_by to avoid duplicates [OK]
Hint: Use find_or_create_by to prevent duplicate seed entries [OK]
Common Mistakes:
  • Creating records without checking duplicates
  • Deleting all data before seeding unnecessarily
  • Passing array directly to create without hashes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard