2016-05-24 1 views
1

Я настроил собственную задачу семян грабли, чтобы заполнить мою базу данных. Моя задача rake настроена так, чтобы циклически перебирать массив массивов один раз (после выполнения) и заполнять базу данных указанными данными. По какой-то причине задача rake работает пять раз, когда я запускаю задачу один раз.Пользовательский файл семян рапса (Rails 4.2.1 Ruby 2.2.3) - Циклирует больше раз, чем один раз, и создает повторяющиеся записи в базе данных

Кроме того, каждая позиция, зацикливавшаяся, создала дополнительную запись значения нуля в базе данных.

После того, как я смотрел на свой код, я не могу рассуждать об этих двух проблемах. Любая помощь высоко ценится!

**testdata.rb** 

questions = [ 
    ["What is the supreme law of the land?\n1) the Ley of the Land\n2) the Article of Law\n3) the Constitution\n4) Article One of the Constitution", "3", "The Constitution is the \"supreme law of the land\" and establishes the basic principles of the US govt. It lists fundamental rights for people living in the USA.", "Version1", "English"], 

    ["The \"supreme law of the land\" is not the Constitution.\n1) True\n2) False", "2", "The Constitution is the \"supreme law of the land\" and establishes the basic principles of the US govt. It lists fundamental rights for people living in the USA.", "Version1", "English"] 
] 

questions.each do | body, correct_answer, explanation, version, language | 
    Question.create(subject_id: 3, body: body, correct_answer: correct_answer, explanation: explanation, version: version, language: language, active: true) 
end 

**test.rake** 

namespace :db do 
    namespace :seed do 
    Dir[File.join(Rails.root, 'db', 'seeds', '*.rb')].each do |testdata| 
     task_name = File.basename(testdata, '.rb').intern  
     desc "Load the seed data from db/seeds/#{task_name}.rb" 
     task task_name => :environment do 
     load(testdata) if File.exist?(testdata) 
     end 
    end 
    end 
end 

**Output in SQLLITE ActiveRecord query after running rake task** 

MacbookAir $rake db:seed:testdata 
MacbookAir $rails c 
Running via Spring preloader in process 23953 
Loading development environment (Rails 4.2.6) 
2.2.1 :001 > Question.all.map{|s| puts s.body} 
Question Load (0.4ms) SELECT "questions".* FROM "questions" ORDER BY "questions"."id" DESC LIMIT 10 
What is the supreme law of the land? 
1) the Ley of the Land 
2) the Article of Law 
3) the Constitution 
4) Article One of the Constitution 
The "supreme law of the land" is not the Constitution. 
1) True 
2) False 
What is the supreme law of the land? 
1) the Ley of the Land 
2) the Article of Law 
3) the Constitution 
4) Article One of the Constitution 
The "supreme law of the land" is not the Constitution. 
1) True 
2) False 
What is the supreme law of the land? 
1) the Ley of the Land 
2) the Article of Law 
3) the Constitution 
4) Article One of the Constitution 
The "supreme law of the land" is not the Constitution. 
1) True 
2) False 
What is the supreme law of the land? 
1) the Ley of the Land 
2) the Article of Law 
3) the Constitution 
4) Article One of the Constitution 
The "supreme law of the land" is not the Constitution. 
1) True 
2) False 
What is the supreme law of the land? 
1) the Ley of the Land 
2) the Article of Law 
3) the Constitution 
4) Article One of the Constitution 
The "supreme law of the land" is not the Constitution. 
1) True 
2) False 
=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil] 

ответ

0

Это может быть старые данные, оставшиеся в вашем дб ... Вы могли бы хотеть попробовать

db:reset

Рельсыdb: задача сброса сбросит базу данных и снова настроит ее. Это функционально эквивалентно rails db: drop db: setup.

rails guide

+0

побежал грабли БД: сброс и до сих пор в конечном итоге с теми же результатами: 5 записей для каждой позиции индекса и одно значение ноль для каждой записи в таблице БД –