我有一个 rake 任务,它使用 FactoryGirl 用种子数据填充我的数据库。例如 -
def create_goals
puts "Creating goals for each subject"
Subject.all.each do |s|
FactoryGirl.create_list :goal, 3, subject_id: s.id
end
end
我有一个新模型——Evaluations
另外belongs_to
两个模型:Students
和Goals
。
目前我有这个:
def create_evaluations
puts "Creating evaluation data for each goal (have you put the kettle on yet?)"
Goal.all.each do |g|
FactoryGirl.create_list :evaluation, 3, goal_id: g.id
end
end
但这显然只给出了具有goal_id
- 我和Student
父母做了同样的事情,但问题是相反的 - 那么如何为具有两个belongs_to
关联的模型制作数据?
更新:
我试过这个:
def create_evaluations
puts "Creating evaluation data for each student and goal"
Student.all.each do |s|
Goal.all.each do |g|
FactoryGirl.create_list :evaluation, 3, student_id: s.id, goal_id: g.id
end
end
end
但无法测试它是否有效,因为我让它运行了约 1 小时并且仍在运行。
更新:它运行这么长时间的原因是因为我忽略了改变它产生的用户数量。我将其更改为只有 2 个用户,它运行得足够快。这是我最终使用的代码(感谢Pierre-Louis Gottfrois的帮助!):
require 'factory_girl_rails'
namespace :db do
desc "Fill db with sample data"
task :populate, :environment do
# warning message
puts "##############################################################"
puts "# if this takes too long, reduce the number of created users #"
puts "##############################################################"
# reset the database
reset_db
# some messages
puts "Database reset. Database population started"
# create users
create_users
#create student_groups for each user
create_student_groups
#create students for each student_group
create_students
#create subjects for each student_group
create_subjects
#create goals for each subject
create_goals
#create evaluation data for each goal
create_evaluations
# success message
puts "The database has been populated successfully"
end
###################
#### METHODS ####
###################
def reset_db
puts "Resetting the database"
Rake::Task['db:reset'].invoke
end
def create_users
puts "Creating users"
FactoryGirl.create_list :user, 2
end
def create_student_groups
puts "Creating student groups for each user"
User.all.each do |u|
FactoryGirl.create_list :student_group, 3, user_id: u.id
end
end
def create_students
puts "Creating students for each student group"
StudentGroup.all.each do |sg|
FactoryGirl.create_list :student, 7, student_group_id: sg.id
end
end
def create_subjects
puts "Creating subjects for each student group"
StudentGroup.all.each do |sg|
FactoryGirl.create_list :subject, 4, student_group_id: sg.id
end
end
def create_goals
puts "Creating goals for each subject"
Subject.all.each do |s|
FactoryGirl.create_list :goal, 3, subject_id: s.id
end
end
def create_evaluations
puts "Creating evaluation data"
Student.all.each_with_index do |s, index|
@goals = Goal.all
@goals.count.times do |i|
FactoryGirl.create_list :evaluation, 3, goal_id: @goals[i].id, student_id: s.id
end
# Counter to track progress
puts "Created data for 'Student #{index}'"
end
end
end