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.
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.
/db/seeds/demo/users.yml /db/seeds/demo/teams.yml /db/seeds/demo/items.yml
Seed tasks in Rails are typical rake tasks.
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.
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:
We aim to have our rake tasks be small, by moving any business logic into matching helper files that are real Ruby scripts.
/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.