2014-07-10 54 views
0

我有一個Rails應用程序,其中Student,GroupStudentGroup模型。團體有很多學生通過StudentGroup。我需要能夠將學生批量添加到一個高效莊園的團隊中。我目前的(慢)代碼是這樣的如果在Rails中不存在批量插入記錄

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

如何'Student.find(PARAMS [:student_emplids])'返回不止一個學生多? – bjhaid

+0

@bjhaid如果'params [:student_emplids]'是一個數組,它將使用'IN()'查詢。 – Unixmonkey

+1

如果是這樣的話,最好使用'where'來清楚指出期望的結果。爲了自己的利益,「find」有點太聰明瞭。 – tadman

回答

1

active_record_bulk_insert寶石添加到您的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} }) 
相關問題