Database Seeding in Rails

The automatically created file db/seeds.rb is a default location for creating seed data for your database. It was introduced in order to stop the practice of inserting seed data in individual migration files, if you accept the premise that migrations should never be used for seeding example or base data required by your application. It is executed with the rake db:seed task (or created alongside the database when you run rake db:setup).

At its simplest, the contents of seed.rb is simply a series of create! statements that generate baseline data for your application, whether it’s default or related to con figuration. For example, let’s add an admin user and some billing codes to a sample app:

User.create!(:login => ‘admin’, :email => ‘admin@tr3w.com’,:password => ‘123’, :password_confirmation => ‘123’,
:authorized_approver => true)

client = Client.create!(:name => ‘Workbeast’, :code => ‘BEAST’)
client.billing_codes.create!(:name => ‘Meetings’, :code => ‘MTG’)
client.billing_codes.create!(:name => ‘Development’, :code => ‘DEV’)

 

Why use the bang version of the create methods? Because otherwise you won’t find out if you had errors in your seed file. An alternative would be to use find_or_create_by methods to make seeding idempotent.

c = Client.find_or_create_by_name_and_code!(‘Workbeast’, ‘BEAST’)
c.billing_codes.find_or_create_by_name_and_code!(‘Meetings’, ‘MTG’)
c.billing_codes.find_or_create_by_name_and_code!(‘Development’, ‘DEV’)

 

Another common seeding practice worth mentioning is calling delete_all prior to creating new records, so that seeding does not generate duplicate records. This practice avoids the need for idempotent seeding routines and lets you be very secure about exactly
what your database will look like after seeding.

User.delete_all
User.create!(:login => ‘admin’, …
Client.delete_all
client = Client.create!(:name => ‘Workbeast’, …

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s