Implement Sample Data into a Rails App Using the Seeds File
This is going to be a fun episode. In this guide we're going to leverage the Rails seeds file to generate sample data for the application. To start, open up the db/seeds.rb file.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

This is going to be a fun episode. In this guide we're going to leverage the Rails seeds file to generate sample data for the application. To start, open up the db/seeds.rb file. As soon as you open the file you'll see the comments give an example of how you can generate data for your application:

# db/seeds.rb

# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
#   cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
#   Mayor.create(name: 'Emanuel', city: cities.first)

In this file you can run scripts and generator commands, all of which will be added to the database.

Now we create some sample data for our application with this code.

# db/seeds.rb

100.times do |post|
  Post.create!(date: Date.today, rationale: "#{post} rationale content")
end

puts "100 Posts have been created"

To run this and generate the sample data, go to terminal and run this command:

bundle exec rake db:setup

Make sure you run this command only in the development environment since it will wipe out all the existing data from the database, and create new records based on the scripts inside seeds.rb file. This is helpful tool for development, but obviously is disastrous if run in production.

large

If you see the output, it has run all the migration files and at the end, we have the message 100 posts have been created. To verify that this worked, open your rails console with the command rails c, and query all the records with the command Post.all

This should bring up all the records.

large

You can also check the number of records with the command Post. count and it should give an output of 100.

In later guides, we are going to use the seeds.rb extensively to add more content. For now, let's push all these changes to the github repository.

Resources