A Fresh Cup is Mike Gunderloy's software development weblog, covering Ruby on Rails and whatever else I find interesting in the universe of software. I'm a full-time software developer: most of my time in recent years has been spent writing Rails, though I've dabbled in many other things and like most people who have been writing code for decades I can learn new stuff as needed.

Currently I'm employed as the Vice President of Engineering at Faria Education Group. If you're interested in working with me, we're often hiring smart developers. Drop me a comment if you're interested or email MikeG1 [at] larkfarm.com.

« Double Shot #450 | Main | Double Shot #449 »

Seed Data in Rails 3

One of the perennial code smells in many Rails applications is the use of migrations as a way to carry seed data (data that needs to be added to the database on deployment). This doesn't work well because it's tough to maintain and doesn't play well with loading up the database from the schema file.

Rails 3 now has a new answer to this: a file convention and a rake task. The file is db/seeds.rb and it can contain arbitrary Ruby code, but generally it will look something like this:

[sourcecode language='ruby']
cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
Mayor.create(:name => 'Daley', :city => cities.first)

This file then gets run by using the new db:seed rake task, or via rake db:setup which runs create, schema:load, and seed in succession.

As with some other parts of Rails, this is the simplest thing that can possibly work. For a somewhat different take (that also works in Rails 2) take a look at Michael Bleigh's seed_fu or my own db-populate.

Reader Comments (3)

what a timely post. thank you.

May 11, 2009 | Unregistered Commenterjosh

I should make a patch that integrates my foundry project into core. Would be useful for stuff like this.

May 11, 2009 | Unregistered CommenterJeremy

I've been using script/runner for this, which hasn't been too horrible as a pain point for me.

May 11, 2009 | Unregistered CommenterNick

PostPost a New Comment

Enter your information below to add a new comment.
Author Email (optional):
Author URL (optional):
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>