Idempotent Seeds

You Reap What You Sow rake db:seed

seeds

When working with database based applications more often than not, some seed data needs to be created. For example, I’ve used seed data to create an admin_user and a few dummy_users so the site can be used upon a fresh install. Some other common cases include things like, list of names of countries/states, list of user roles, list of permissions etc.
This post is about some ideas to manage seed data in a Ruby on Rails project.

In a Rails application seeds can be put at two places

  • db/seeds.rb [Standard practice]
  • db/migrate/232422_some_migration.rb [*its a possibility]

db/seeds.rb is the obvious place for seeds. Don’t mess around with it unless absolutely necessary.

Some points to keep in mind when sowing seeds:

  • Handling large seed data
    • Split seed files into multiple files clearly indicating your objects and business logic. A sample might look like
              |-app
                |-db
                  -seeds.rb
                  |-seeds
                    -user.rb
                    -roles.rb
                    -plans.rb
    •  Inside seeds.rb require sub seed-files as
      require 'seeds/user.rb'
      require 'seeds/roles.rb'
      require 'seeds/plans.rb'
    • If number of seeds for a business object is large, consider loading it from yaml files. Keeping business logic separate from data is a good practice.
  • Idempotent seeds
    • Idempotent,  a mathematical term that means that something remains the same when some operation is applied to it, using itself as input.
    • For example, multiplication by identity element  5 X 1 = 5.
    • Having idempotent seed files means, they can be run multiple times without causing any issue.
    • Instead of creating or updating objects blindly, it first tries to find the object and check its state.
Advertisements