📖 Scenario: You are building a simple Rails app to manage a bookstore. You want to add some initial books to your database so you can see them when you run the app.
🎯 Goal: Create seed data for the Book model with exact titles and authors. Then configure a count variable to track how many books you add. Finally, write the code to insert these books into the database using Rails seed conventions.
📋 What You'll Learn
Create a list of books with exact titles and authors
Add a variable to count the number of books
Use a loop to create each book record in the database
Ensure the seed file ends with a message showing how many books were added
💡 Why This Matters
🌍 Real World
Seed data helps you quickly fill your app's database with useful starting information, so you can test and develop features without manual data entry.
💼 Career
Knowing how to write seed files is important for backend and full-stack developers working with Rails to set up databases efficiently.
Progress0 / 4 steps
1
Create the books list
Create a variable called books that holds an array of hashes. Each hash should have the keys :title and :author with these exact entries: { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' }, { title: '1984', author: 'George Orwell' }, and { title: 'To Kill a Mockingbird', author: 'Harper Lee' }.
Ruby on Rails
Hint
Use an array [] with hashes {} inside. Each hash needs :title and :author keys.
2
Add a book count variable
Create a variable called book_count and set it to 0. This will keep track of how many books you add to the database.
Ruby on Rails
Hint
Just write book_count = 0 below the books array.
3
Create books in the database
Use a books.each do |book| loop to create each book in the database with Book.create!(title: book[:title], author: book[:author]). Inside the loop, increase book_count by 1 using book_count += 1.
Ruby on Rails
Hint
Use books.each do |book| ... end and inside call Book.create! with the right keys. Don't forget to add book_count += 1.
4
Add a completion message
Add a final line that outputs a message with puts showing exactly: "Added #{book_count} books to the database."
Ruby on Rails
Hint
Use puts with double quotes and #{book_count} inside to show the number.
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
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.
Step 2: Identify the correct purpose
Among the options, only filling the database with initial example data matches the purpose of seed data.
Final Answer:
To fill the database with initial example data for testing and development -> Option D
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
Step 1: Recall the command to run seed data
The standard command to load seed data in Rails is bin/rails db:seed.
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.
Final Answer:
bin/rails db:seed -> Option B
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
Step 1: Understand the loop and index
The loop runs 3 times with i values 0, 1, 2.
Step 2: Calculate user names
Each user name is "User " plus i + 1, so names are "User 1", "User 2", "User 3".
Final Answer:
["User 1", "User 2", "User 3"] -> Option C
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
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
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.
Step 2: Verify other options
Calling User.create multiple times is allowed. Names do not have to be unique unless validated. Loop is optional.
Final Answer:
Missing value for name in the last User.create call -> Option A
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
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.
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.
Final Answer:
['Books', 'Movies', 'Music'].each do |name|
Category.find_or_create_by(name: name)
end -> Option A
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 unknownstrongwhile earning +1 Grip toward your certificate.