ruby
32 lines · 5 steps
Batching bulk inserts in Rails
A BulkImporter chunks records into fixed-size batches and inserts each with a single deduplicated SQL statement.
Explained by
highlit
1class BulkImporter
2 BATCH_SIZE = 500
3
4 def initialize(records)
5 @records = records
6 end
7
8 def import!
9 inserted_ids = []
10
11 @records.each_slice(BATCH_SIZE) do |batch|
12 rows = batch.map do |record|
13 {
14 email: record.fetch(:email).downcase.strip,
15 name: record[:name],
16 created_at: Time.current,
17 updated_at: Time.current
18 }
19 end
20
21 result = User.insert_all(
22 rows,
23 unique_by: :email,
24 returning: %w[id]
25 )
26
27 inserted_ids.concat(result.rows.flatten)
28 end
29
30 inserted_ids
31 end
32end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Slicing records into fixed batches keeps memory and SQL statement size bounded on large imports.
- 2insert_all bypasses model callbacks, so timestamps and normalization must be set manually.
- 3unique_by lets the database skip duplicates atomically instead of checking in Ruby.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
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
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 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/batching-bulk-inserts-in-rails-explained-ruby-4d3c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.