This is inspired by http://sixarm.com/about/rails-seed-data.html which i noticed had some errors.
Seed Data in YAML files
We use the Rails convention of putting our seed data files here:
/db/seeds/
We create a YAML file for our seed users:
/db/seeds/users.yml
The users YAML file defines each user’s fields like this:
Rake task to load seed data
We use the Rails convention of putting rake tasks here:
/lib/tasks/
We use a rake file for our seeds:
/lib/tasks/db_seed_users.rake
The task provides the rake namespace, runs any setup tasks, then calls a normal ruby method:
TIP - the desc is required if you want your task to show up with rake -T
The normal ruby method loads the YAML file and iterates on each user:
To run the rake task:
$ rake db:seed:users
To view your rake tasks:
$ rake -T
Remember, your tasks will not show up unless you add a desc
How to make seeds run more than once
We want to be able to run our seed task more than once and still get produce same set of users.
To do this, we add code that checks to see if the user already exists, and if so, skips creating that user:
Example file looks like this: