Rails Seed Data With DB Seed and Rake

Rails seed data includes the minimal information an app needs to run correctly.

For example if a Rails app has a select box that says "Choose a country", then the app needs a list of countries. The seed data is the list of countries, typically created in a ruby script, and possibly loading the countries from a fixtures file, or spreadsheet file.

Example:

  /db/seeds.rb
  /db/seeds/countries.yml

Rails Seed Data for a Demo

We also create seed data for development, testing, production, and a demo.

For example our seed data for a demo has some demo user accounts, some demo teams like "Alpha Team" and "Beta Team", some demo items like "Apple" and "Banana", and various Rails associations.

Example:

  /db/seeds/demo/users.yml
  /db/seeds/demo/teams.yml
  /db/seeds/demo/items.yml

Rake Seed Tasks

Seed tasks in Rails are typical rake tasks.

For example:

  /lib/tasks/db_seed_countries.rake

We write our seed tasks to be runnable more than once. When the seed task is creating a record, the task checks if the record already exists. If so, the task skips it. This ensures that we don't accidentally create the same user more than once in the database.

DB Seed Namespace

We like to use the rake namespace "db:seed" because it matches Rails. We use the namespace "db:seed:demo" for our demo data.

For example our demo users namespace:

  namespace :db do
    namespace :seed do
      namespace :demo do
        namespace :users do
          ...
        end
      end
    end
  end

We typically have a default task that calls three tasks:

  namespace :db do
    namespace :seed do
      namespace :demo do
        namespace :users do

	  task :default => [:before, :load, :after]

          task :before do
            ...
          end

          task :load do
            ...
          end

          task :after do
            ...
          end

        end
      end
    end
  end

To run the rake task:

  rake db:seed:demo:users:default

Rake Seed Task Helpers

We aim to have our rake tasks be small, by moving any business logic into matching helper files that are real Ruby scripts.

Example:

  /lib/db_seed_users.rb
  /lib/db_seed_teams.rb
  /lib/db_seed_items.rb

This helps us share the Ruby code among multiple tasks, and also makes it easier for us to develop and maintain the rake tasks separately from the business logic.



What's Next?

blog comments powered by Disqus