Homepage
free software, web technologies and heavy metal coding (and ruby of course)

Idempotent seeds in rails

This post first appeared on the Panter Blog:

blog.panter.ch/2015/08/05/idempotent-seeds-in-rails.html

Database seeds are a very handy tool in rails. They ease setting up a proper development environment with meaningful data. One issue with the out of the box seeds is though that they are not idempotent per se. While developing an application you don’t want to always reset the database to get a proper seed state. If the seeds were idempotent, you could run rake db:seed as many time as you’d like without corrupting the integrity of your data. Just as migrations, running the seeds should only update your database if necessary.

A simple helper method helps creating idempotent data easily.

The actual seed could look something like this.

That’s it. Now execute rake db:seed a few times to get back your confidence in your seeds.

EDIT

I packed the contents of this post into a gem called SeedBox.