Skip to content

Instantly share code, notes, and snippets.

@raghubetina
Last active December 8, 2020 15:45
Show Gist options
  • Save raghubetina/9b1dd3f6fcb0a459b6244c379628c675 to your computer and use it in GitHub Desktop.
Save raghubetina/9b1dd3f6fcb0a459b6244c379628c675 to your computer and use it in GitHub Desktop.
Seeding your database

Seeding your database

It is very helpful to take the time to pre-populate your database with some dummy data before you start working on any features. It's nice to have some data to look at to see whether you are going down the right path.

It's also very helpful to other developers on the project, so they can get started quickly right after they clone.

Here are two ways to create seed data:

Manually + seed_dump

The simplest way is to use the forms that were written by the generator, and manually enter some realistic data.

(It might help to at least replace the <input type="text" ...>s for foreign keys with <%= select_tag ... %>s before doing this, to make your life a little easier.)

Once you've added some data to your tables manually, we can use the seed_dump gem to automatically generate a db/seeds.rb file for us:

Add the gem:

# Gemfile

gem "seed_dump"
bundle install

Then run the following command:

rake db:seed:dump EXCLUDE=[]

This will replace your existing db/seeds.rb file (say "yes" if it asks your permission to overwrite). (You could also choose to exclude certain columns.)

You can now rake db:seed whenever you want to re-create your data; for example, if things get into a bad state, you can

rake db:drop
rake db:migrate
rake db:seed

to reset. You can re-run rake db:seed:dump EXCLUDE=[] at any time to overwrite your db/seeds.rb again with the current state of your tables.

Write some Ruby yourself

The other way to go is to write some plain old Ruby yourself to do the work of CRUDing some starter data. I often use the faker gem to help with this; here is an example.

From a CSV

Here is a guide to seeding from a CSV file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment