如果Rails中不存在,则批量插入记录

时间:2014-07-10 13:39:33

标签: ruby-on-rails ruby activerecord ruby-on-rails-4

我有一个包含StudentGroupStudentGroup模型的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

我如何改进此代码?

1 个答案:

答案 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} })