Monday
May112009
Seed Data in Rails 3
Monday, May 11, 2009 at 8:07AM
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
[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
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.
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.
I should make a patch that integrates my foundry project into core. Would be useful for stuff like this.
I've been using script/runner for this, which hasn't been too horrible as a pain point for me.