Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails recommended way to add sample data

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
like image 994
Lee Avatar asked Jul 10 '13 20:07

Lee


1 Answers

You should not fill your database with sample data via db:seed. That's not the purpose of the seeds file.

db:seed is for initial data that your app needs in order to function. It's not for testing and/or development purposes.

What I do is to have one task that populates sample data and another task that drops the database, creates it, migrates, seeds and populates. The cool thing is that it's composed of other tasks, so you don't have to duplicate code anywhere:

# lib/tasks/sample_data.rake
namespace :db do
  desc 'Drop, create, migrate, seed and populate sample data'
  task prepare: [:drop, :create, "schema:load", :seed, :populate_sample_data] do
    puts 'Ready to go!'
  end

  desc 'Populates the database with sample data'
  task populate_sample_data: :environment do
    10.times { User.create!(email: Faker::Internet.email) }
  end
end
like image 200
Agis Avatar answered Oct 14 '22 11:10

Agis