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 Rails developer and contributor, available for long- or short-term consulting, with solid experience in working as part of a distributed team. If you'd like to hire me, drop me a line. I'm also the author of Rails Rescue Handbook and Rails Freelancing Handbook.

Navigation
« Double Shot #450 | Main | Double Shot #449 »
Monday
May112009

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)
[/sourcecode]

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):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>