Building a Ruby on Rails (RoR) API Part V: Seeding

Seeding the DB

  ·   2 min read

Sometimes, as developers we need to have as many data as possible in our DBs to test different things. I’ve came up with a solution to populate the DB using Faker. I’m setting the seed as it would be in a regular Rails task. I’ve created anothre folder lib, where this fakers live, here’s an easy example.

 1# /lib/tasks/containers.rake
 2unless Rails.env.production?
 3  require 'faker'
 4
 5  namespace :db do
 6    namespace :seed do
 7      desc "Seeds up to 500 different containers"
 8      task containers: :environment do
 9        500.times do |index|
10          Container.create!(
11              name: Faker::Beer.yeast
12          )
13        end
14        p "Created #{Container.count} containers"
15      end
16    end
17  end
18end

This is: “if you’re not in production populate the DB like this”. I have one of this per each model I need to populate in the DB. Notice how the namespaces make it match with a regular rake task.

Now, let’s talk about the file that fires the populate task:

/populate

1#!/bin/sh
2rake db:seed:producers
3rake db:seed:warehouses
4rake db:seed:places
5rake db:seed:products
6rake db:seed:containers
7rake db:seed:routes
8rake db:seed:crops
9rake db:seed:packages

The only need to do is to guarantee that it is executable: $ chmod a+x populate, so you can fire it up: ./populate. It will run each lib task in the specified order, and depending on how many you’ve wrote and how many iteration each file has to do, it will take some time.