How to Seed Database in Rails: Simple Guide with Examples
In Rails, you seed the database by adding data to the
db/seeds.rb file and then running rails db:seed. This command loads the seed file and inserts the data into your database.Syntax
Use the db/seeds.rb file to write Ruby code that creates records in your database. Then run rails db:seed in the terminal to execute this file and add the data.
Key parts:
db/seeds.rb: The file where you define seed data.rails db:seed: Command to run the seed file.
ruby
User.create(name: 'Alice', email: 'alice@example.com') Product.create(name: 'Book', price: 9.99)
Example
This example shows how to seed a simple database with users and products. Running rails db:seed will add these records.
ruby
# db/seeds.rb User.create(name: 'Alice', email: 'alice@example.com') User.create(name: 'Bob', email: 'bob@example.com') Product.create(name: 'Book', price: 9.99) Product.create(name: 'Pen', price: 1.49)
Output
Created 2 users and 2 products in the database.
Common Pitfalls
Common mistakes include:
- Not running
rails db:seedafter editingseeds.rb. - Running seeds multiple times without clearing data, causing duplicates.
- Using
create!without handling validation errors.
To avoid duplicates, use find_or_create_by instead of create.
ruby
# Wrong way (duplicates on multiple runs) User.create(name: 'Alice', email: 'alice@example.com') # Right way (avoids duplicates) User.find_or_create_by(email: 'alice@example.com') do |user| user.name = 'Alice' end
Quick Reference
| Command | Description |
|---|---|
| rails db:seed | Runs the seed file to populate the database |
| rails db:reset | Drops, creates, migrates, and seeds the database |
| find_or_create_by | Creates a record only if it doesn't exist to avoid duplicates |
| db/seeds.rb | File where seed data is defined |
Key Takeaways
Write seed data in db/seeds.rb using Ruby code to create records.
Run rails db:seed to load seed data into your database.
Use find_or_create_by to prevent duplicate records when seeding multiple times.
Edit seeds.rb and rerun rails db:seed whenever you want to update seed data.
Use rails db:reset to clear and reseed your database in one command.