我有一个包含Student
,Group
和StudentGroup
模型的Rails应用程序。小组通过StudentGroup
有很多学生。我需要能够以高效的庄园将学生批量添加到一个小组。我当前(慢)的代码是这样的
def add_students
if params[:student_emplids].presence
Student.find(params[:student_emplids]).each do |student|
@group.student_groups.where(student: student).first_or_create
end
end
respond_with @group
end
我如何改进此代码?
答案 0 :(得分:1)
将active_record_bulk_insert gem添加到Gemfile
并捆绑
#Get the ids of the students
student_ids = Student.where(id: *params[:student_emplids]).pluck(:id)
#Get `students` with `student_groups`
student_with_group_ids = StudentGroup.where(student_id: *params[:student_emplids]).pluck(:student_id)
#create a list of student_groups and bulk_insert them
StudentGroup.bulk_insert((student_ids - student_with_group_ids).map { |id| {:student_id => id, :group_id => @group.id} })