Loading “Seed” Data in Rails

A Rails application needs some data to exist in database before the application can be run. It is called ‘seed’ data.
This post shows how to create a rake task that loads ‘seed’ data. Data is stored in *.yml files.

‘Seed’ data in YAML files

Let’s create some categories and products and load them into our database. We assume that we have two tables ‘products’ and ‘categories’.

The SQL script to create the tables:




 

We will store our data in *.yml files in the following format:




 




 

Rake task

We create a rake task in the file ‘lib/tasks/db_seed_products.rake’:

 




It calls our method Db::Dbloader.load_all_YAML_from_files stored in our library ‘lib/db/dbloader.rb’:

 




In this solution it is important that file names for *.yml files correspond the models. So data from products.yml correspond to Product model class and data from categories.yml inserted into database using Category model class.

 

To run rake task:

rake db:seed:products:load

 

 

Use FactoryGirl

You can use FactoryGirl to define ‘seed’ data in *.rb files.

 

Define factories in file ‘spec/factories/categories.rb’:

 




Then we can load data to db using FactoryGirl.create.

Replace

cls.create attr

in dbloader.rb with this:




 

 

 

All code presented in this post is available on Github gist.