0
0
Ruby on Railsframework~5 mins

Seed data in Ruby on Rails

Choose your learning style9 modes available
Introduction

Seed data helps you fill your app's database with example information quickly. It makes testing and development easier by starting with known data.

When you want to add default users or products to your app after setup.
When you need sample data to test features without typing everything manually.
When sharing your app with others so they see example content right away.
When resetting your database during development and want to reload example data.
Syntax
Ruby on Rails
# db/seeds.rb
Model.create(attribute: 'value', other_attribute: 123)

# Then run:
bin/rails db:seed

The db/seeds.rb file is where you write code to add data.

Run bin/rails db:seed to load the data into your database.

Examples
Adds one user named Alice with an email.
Ruby on Rails
User.create(name: 'Alice', email: 'alice@example.com')
Adds multiple products at once using an array.
Ruby on Rails
Product.create([{name: 'Book', price: 10}, {name: 'Pen', price: 2}])
Creates 10 posts with numbered titles using a loop.
Ruby on Rails
10.times { |i| Post.create(title: "Post #{i + 1}", body: 'Sample text') }
Sample Program

This seed file adds one user and two products to the database. Running bin/rails db:seed will insert these records so you can use them in your app.

Ruby on Rails
# db/seeds.rb
User.create(name: 'John Doe', email: 'john@example.com')
Product.create([{name: 'Notebook', price: 5}, {name: 'Pencil', price: 1}])

# Run this command in terminal:
bin/rails db:seed
OutputSuccess
Important Notes

Running db:seed does not clear existing data; use db:reset to drop and recreate the database with seeds.

You can add any Ruby code in seeds.rb, like loops or conditionals, to create complex data.

Summary

Seed data fills your database with example info for easy testing and development.

Write seed code in db/seeds.rb and run bin/rails db:seed to load it.

Use loops and arrays to add many records quickly.