ruby 45 lines · 8 steps

Bulk task reordering with upsert_all in Rails

A controller action reorders tasks by mapping incoming IDs to positions and persisting them in one batched upsert.

Explained by highlit
1class TasksController < ApplicationController
2 before_action :set_project
3 
4 def reorder
5 ids = reorder_params.fetch(:task_ids)
6 tasks = @project.tasks.where(id: ids).index_by(&:id)
7 
8 updates = ids.each_with_index.map do |id, index|
9 task = tasks[id.to_i]
10 next unless task
11 
12 { id: task.id, position: index + 1, updated_at: Time.current }
13 end.compact
14 
15 if updates.empty?
16 head :unprocessable_entity
17 return
18 end
19 
20 Task.transaction do
21 Task.upsert_all(updates, unique_by: :id)
22 end
23 
24 respond_to do |format|
25 format.turbo_stream do
26 render turbo_stream: turbo_stream.replace(
27 "project_#{@project.id}_tasks",
28 partial: "tasks/list",
29 locals: { tasks: @project.tasks.order(:position) }
30 )
31 end
32 format.json { head :no_content }
33 end
34 end
35 
36 private
37 
38 def set_project
39 @project = current_user.projects.find(params[:project_id])
40 end
41 
42 def reorder_params
43 params.permit(task_ids: [])
44 end
45end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Loading records into a hash keyed by id avoids an N+1 lookup when matching against an ordered input list.
  2. 2upsert_all writes many rows in a single statement, far cheaper than saving each record in a loop.
  3. 3Scoping queries through the current user's associations enforces authorization without a separate check.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Bulk task reordering with upsert_all in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code