0
0
Ruby on Railsframework~30 mins

Seed data in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Seed Data in Rails
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use puts with double quotes and #{book_count} inside to show the number.