2013-07-10 2 views
7

나는 레이크 스크립트를 아래에 비슷한 있지만, 데이터베이스를 삭제할 필요없이이 작업을 수행하는 더 효율적인 방법이 있는지 궁금, 모든 마이그레이션을 실행하고 데이터베이스 및 그런 다음 샘플 데이터를 추가 하시겠습니까?레일 예제 데이터를 추가하는 것이 좋습니다

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 
+0

테스트 환경 용입니까? –

+0

이것은 개발 환경을위한 것이다 – Lee

답변

-3

나는 rake db:seed을 자급 자족하는 것이 좋습니다. 즉,로드가 필요한 샘플 데이터를로드하는 동안 모든 손상없이 여러 번 실행할 수 있어야합니다.

그래서, 당신의 연구를 들면, DB : 시드 작업은 다음과 같이 뭔가를 수행해야합니다

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

은이 이상 이상 이상 실행할 수 있으며 항상 10 임의의 사용자와 끝날 보장된다.

개발 용입니다. 이 경우 db : seed로 저장하지 않으므로 프로덕션 환경에서 실행될 수 있습니다. 그러나 필요한만큼 자주 다시 실행할 수있는 유사한 레이크 작업에 넣을 수 있습니다.

+8

'db : seed'는 샘플 데이터로 데이터베이스를 채우는 올바른 방법이 아니다. – Agis

23

아니요db:seed을 통해 샘플 데이터로 데이터베이스를 채우십시오. 그것은 씨 파일의 목적이 아닙니다.

db:seed은 기능을 수행하기 위해 의 앱이 필요한 초기 데이터 용입니다. 테스트 및/또는 개발 목적이 아닙니다.

내가 수행하는 작업은 샘플 데이터를 채우는 작업 하나와 데이터베이스를 삭제하고 생성하고 마이그레이션하고 시드하고 채우는 다른 작업을 채우는 것입니다. 멋진 일은 다른 작업으로 구성되므로 어디서나 코드를 복제 할 필요가 없습니다.

# 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 
+2

이것은 받아 들여진 응답 일 것입니다 : 씨앗 대 작업 – yamori

+0

@agis 왜 이렇게하면 일부 ActiveRecord 속성이 사라지게 될까요? https://stackoverflow.com/questions/44381014/the-case-of-the-disappearing-activerecord-attribute –

+0

이것은 'migrate'대신'schema : load'이어야합니다. 데이터베이스를 재시작 할 때마다 마이그레이션을 재실행하면 안되며, db/schema.rb가 그 것이다. 공식 가이드 : http://guides.rubyonrails.org/active_record_migrations.html#what-are-schema-files-for-questionmark – brainbag

관련 문제