File tree Expand file tree Collapse file tree
lib/concepts/school_student Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -49,16 +49,25 @@ def normalize_student_params(students)
4949 end
5050
5151 def create_student_roles ( school , responses )
52- # Bulk check which roles already exist to avoid N+1 queries
5352 user_ids = responses . pluck ( :id )
54- existing_roles = Role . student . where ( school_id : school . id , user_id : user_ids ) . index_by ( &:user_id )
53+ existing_user_ids = Role . student . where ( school_id : school . id , user_id : user_ids ) . pluck ( :user_id )
54+ new_user_ids = user_ids - existing_user_ids
5555
56- # Create only the missing roles
57- user_ids . each do |user_id |
58- next if existing_roles [ user_id ]
56+ return if new_user_ids . empty?
5957
60- Role . create! ( role : :student , school_id : school . id , user_id : user_id )
58+ # Use insert_all to avoid N+1 INSERT queries
59+ new_roles = new_user_ids . map do |user_id |
60+ {
61+ role : Role . roles [ :student ] ,
62+ school_id : school . id ,
63+ user_id : user_id
64+ }
6165 end
66+
67+ # We know the school and uniqueness is ok at this stage, so we can skip validations
68+ # rubocop:disable Rails/SkipsModelValidations
69+ Role . insert_all ( new_roles , unique_by : %i[ user_id school_id role ] )
70+ # rubocop:enable Rails/SkipsModelValidations
6271 end
6372
6473 def format_student_responses ( responses )
You can’t perform that action at this time.
0 commit comments