In this step, you will learn how to automate the adding of seed data to the web app’s database.
In VS Code, open the Ruby code file db/seeds.rb
in the editor.
seeds.rb
is a script that can be run when initializing the web app to add starter data to the database. Note that the file currently contains only comments.
Add to seeds.rb
the following four Person.create!
calls immediately following the comments:
Person.create!(first_name: 'Homer', last_name: 'Simpson', height_inches: 72, weight_lbs: 241)
Person.create!(first_name: 'Marge', last_name: 'Simpson', height_inches: 102, weight_lbs: 139)
Person.create!(first_name: 'Ned', last_name: 'Flanders', height_inches: 70, weight_lbs: 246)
Person.create!(first_name: 'Edna', last_name: 'Krabappel', height_inches: 67, weight_lbs: 156)
Note that we use create!
(instead of create
without the !
) in the seeds.rb
, because the !
version ensures that error messages will be shown in the event of an error. The version without the !
will not throw exceptions on certain errors, failing silently, which can be very confusing.
To reset the database (emptying it of data), run this command in the terminal:
rails db:migrate:reset
Run this PostgreSQL command to confirm that the table people
was emptied:
psql --command="SELECT * FROM people" practice_app_development
Note that the people
table now contains 0 rows.
To run the seeds.rb
script, run this command:
rails db:seed
Run this PostgreSQL command to confirm that the seed data was added to the table people
:
psql --command="SELECT * FROM people" practice_app_development
Note that the people
table now contains 4 rows corresponding to the four create!
calls in the seeds.rb
script.