Lesson Tuesday

When we need to install a database on a new device or in a new environment, we may want to add default data to the tables in the process. This is called seeding the database and allows us to enter data quickly and easily to existing database tables.

Seeding a Database


In Rails, we seed a database by using Rake and the db/seeds.rb file. In the example below, we want to default 6 records to the trees table, each with two properties: common_name and latin_name.

db/seeds.rb
tree_list = [
  [ "Oak", "Quercus" ],
  [ "Pine", "Pinus" ],
  [ "Sycamore", "Platanus" ],
  [ "Alder", "Alnus" ],
  [ "Birch", "Betula"],
  [ "Cherry", "Prunus"]
]

tree_list.each do |common, latin|
  Tree.create( common_name: common, latin_name: latin )
end

Once the seeds file is in place in the db folder, we can run the following Rake task in the terminal:

$ rake db:seed

This will populate the trees database by going through each item in the array tree_list and creating a new record.

If we are creating a new environment on another device, we can run $ rake db:setup which will create the database, tables and add the seeded data from the seeds file.

Lesson 26 of 34
Last updated July 14, 2022