What is the best way to seed a database in Rails? What is the best way to seed a database in Rails? ruby ruby

What is the best way to seed a database in Rails?


Updating since these answers are slightly outdated (although some still apply).

Simple feature added in rails 2.3.4, db/seeds.rb

Provides a new rake task

rake db:seed

Good for populating common static records like states, countries, etc...

http://railscasts.com/episodes/179-seed-data

*Note that you can use fixtures if you had already created them to also populate with the db:seed task by putting the following in your seeds.rb file (from the railscast episode):

require 'active_record/fixtures'Fixtures.create_fixtures("#{Rails.root}/test/fixtures", "operating_systems")

For Rails 3.x use 'ActiveRecord::Fixtures' instead of 'Fixtures' constant

require 'active_record/fixtures'ActiveRecord::Fixtures.create_fixtures("#{Rails.root}/test/fixtures", "fixtures_file_name")


Usually there are 2 types of seed data required.

  • Basic data upon which the core of your application may rely. I call this the common seeds.
  • Environmental data, for example to develop the app it is useful to have a bunch of data in a known state that us can use for working on the app locally (the Factory Girl answer above covers this kind of data).

In my experience I was always coming across the need for these two types of data. So I put together a small gem that extends Rails' seeds and lets you add multiple common seed files under db/seeds/ and any environmental seed data under db/seeds/ENV for example db/seeds/development.

I have found this approach is enough to give my seed data some structure and gives me the power to setup my development or staging environment in a known state just by running:

rake db:setup

Fixtures are fragile and flakey to maintain, as are regular sql dumps.


factory_bot sounds like it will do what you are trying to achieve. You can define all the common attributes in the default definition and then override them at creation time. You can also pass an id to the factory:

Factory.define :theme do |t|  t.background_color '0x000000'  t.title_text_color '0x000000',  t.component_theme_color '0x000000'  t.carrier_select_color '0x000000'  t.label_text_color '0x000000',  t.join_upper_gradient '0x000000'  t.join_lower_gradient '0x000000'  t.join_text_color '0x000000',  t.cancel_link_color '0x000000'  t.border_color '0x000000'  t.carrier_text_color '0x000000'  t.public trueendFactory(:theme, :id => 1, :name => "Lite", :background_color => '0xC7FFD5')Factory(:theme, :id => 2, :name => "Metallic", :background_color => '0xC7FFD5')Factory(:theme, :id => 3, :name => "Blues", :background_color => '0x0060EC')

When used with faker it can populate a database really quickly with associations without having to mess about with Fixtures (yuck).

I have code like this in a rake task.

100.times do    Factory(:company, :address => Factory(:address), :employees => [Factory(:employee)])end