0
0
RailsHow-ToBeginner · 3 min read

How to Use db:seed in Rails to Populate Your Database

In Rails, you use rails db:seed to run the code inside db/seeds.rb, which populates your database with initial data. This command helps you add default records or test data quickly after setting up your database.
📐

Syntax

The rails db:seed command runs the Ruby code inside the db/seeds.rb file. This file contains instructions to create or update records in your database.

Use the command in your terminal inside the Rails project folder:

  • rails db:seed - runs the seed file to add data
  • rails db:seed:replant - clears the database and runs seeds fresh (Rails 6+)
bash
rails db:seed
💻

Example

This example shows how to add some users to your database using db/seeds.rb. When you run rails db:seed, these users will be created.

ruby
User.create(name: "Alice", email: "alice@example.com")
User.create(name: "Bob", email: "bob@example.com")
Output
2 users created
⚠️

Common Pitfalls

Common mistakes when using db:seed include:

  • Running rails db:seed without having the database migrated first.
  • Writing seed code that creates duplicate records every time you run it.
  • Not handling errors inside db/seeds.rb, which can stop the seeding process.

To avoid duplicates, use find_or_create_by instead of create.

ruby
User.create(name: "Alice", email: "alice@example.com") # Wrong: duplicates on rerun

User.find_or_create_by(email: "alice@example.com") do |user|
  user.name = "Alice"
end # Right: avoids duplicates
📊

Quick Reference

Tips for using db:seed effectively:

  • Always run rails db:migrate before seeding.
  • Use find_or_create_by to prevent duplicate records.
  • Keep db/seeds.rb simple and idempotent (safe to run multiple times).
  • Use rails db:seed:replant to reset and seed fresh in Rails 6+.

Key Takeaways

Run rails db:seed to execute the code in db/seeds.rb and add initial data.
Always migrate your database before seeding to avoid errors.
Use find_or_create_by in seeds to prevent duplicate records on multiple runs.
Keep seed scripts simple and safe to run multiple times.
Use rails db:seed:replant to clear and reseed your database in Rails 6 and newer.