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
java
@Configuration @EnableWebSecurity public class ResourceServerConfig {
Configuring a JWT resource server in Spring
oauth2
jwt
authorization
Intermediate
8 steps
ruby
require "openssl" require "json" require "base64"
Building signed session tokens in Ruby
hmac
authentication
cryptography
Intermediate
8 steps
ruby
class Product < ApplicationRecord belongs_to :category, touch: true has_many :reviews, dependent: :destroy
How Rails models wire up associations
active record
associations
validations
Intermediate
7 steps
ruby
require "net/http" require "json" require "uri" require "base64"
Paginating an HTTP API with a Ruby enumerator
pagination
http
enumerator
Intermediate
7 steps
ruby
class DateRangeMerger def initialize(ranges) @ranges = ranges end
Merging overlapping date ranges in Ruby
sorting
interval-merging
enumerable
Intermediate
5 steps
ruby
module SlowQueryLogger SLOW_QUERY_THRESHOLD_MS = 200.0 IGNORED_PAYLOAD_NAMES = %w[SCHEMA TRANSACTION].freeze
Logging slow SQL queries in Rails
instrumentation
logging
pub-sub
Intermediate
7 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.