Rails recommended way to add sample data

ruby-on-rails

Solution

I would suggest making `rake db:seed` self sufficient. By which I mean, you should be able to run it multiple times without it doing any damage, while ensuring that whatever sample data you need loaded gets loaded.

So, for your researches, the db:seed task should do something like this:

User.destroy_all
10.times do
  researcher = User.new
  researcher.email = Faker::Internet.email
  researcher.save!
end

You can run this over and over and over and are ensured you will always end up with 10 random users.

I see this is for development. In that case, I wouldn't put it in db:seed as that might get run in production. But you can put it in a similar rake task that you can re-run as often as needed.

Problem

I have a Rake script similar to below,but I am wondering if there is a more efficient way to do this, without having to drop the database, run all the migrations, reseed the database and then add the sample data? ``` namespace :db do desc 'Fill database with sample data' task populate: :environment do purge_database create_researchers create_organisations add_survey_groups_to_organisations add_members_to_survey_groups create_survey_responses_for_members end end def purge_database puts 'about to drop and recreate database' system('rake db:drop') puts 'database dropped' system('rake db:create') system('rake db:migrate') system('rake db:seed') puts 'Database recreated...' end def create_researchers 10.times do researcher = User.new researcher.email = Faker::Internet.email researcher.save! end end ```

Original source