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 => ‘firstname.lastname@example.org’,: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’)
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.create!(:login => ‘admin’, …
client = Client.create!(:name => ‘Workbeast’, …