Seeding Data

Sometimes, when we’re working with out database and testing out applications, it would be great to have some ‘dummy’ data added or some required recorded added to try stuff out.

ActiveRecord makes this pretty easy. To add initial data after a database is created, it has a built-in ‘seeds’ feature. It’s a quick way to feed in default values or quickly make a fresh installation on another server or computer. It’s also really useful if you’re reloading the database from your local machine to a deployment/live environment.

To use this feature, just create a file in your db folder called seeds.rb and add some ruby code to create/add/edit/delete records.

For example this is a good template

# delete anything that already exists
Task.delete_all
# reset the primary ids to start at 1 
# when the next item is inserted/created
Task.reset_autoincrement

# create a bunch of data to test with
Task.create!([{ name: "Example task", list_id: 1 } ])
Task.create!([{ name: "Example 2", list_id: 1 } ])
Task.create!([{ name: "Example 3", list_id: 2 } ])
Task.create!([{ name: "Example 4", list_id: 1 } ])

Once the file is created, pop open a terminal window and type:

rake db:seed

Find out more

Migrations and Seed Data

×

Subscribe

The latest tutorials sent straight to your inbox.