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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Loading records into a hash keyed by id avoids an N+1 lookup when matching against an ordered input list.
- 2upsert_all writes many rows in a single statement, far cheaper than saving each record in a loop.
- 3Scoping queries through the current user's associations enforces authorization without a separate check.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/bulk-task-reordering-with-upsert_all-in-rails-explained-ruby-7c6c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.