class Import < ApplicationRecord
include ActionView::RecordIdentifier
enum status: { pending: 0, processing: 1, completed: 2, failed: 3 }
has_one_attached :file
def progress
return 0 if total_rows.to_i.zero?
((processed_rows.to_f / total_rows) * 100).round
end
def broadcast_progress
broadcast_replace_to(
self,
target: dom_id(self, :progress),
partial: "imports/import",
locals: { import: self }
)
end
end
require "csv"
class ImportRowsJob < ApplicationJob
queue_as :default
BROADCAST_EVERY = 50
def perform(import)
import.update!(status: :processing, processed_rows: 0)
rows = CSV.parse(import.file.download, headers: true)
import.update_columns(total_rows: rows.size)
processed = 0
rows.each do |row|
Contact.upsert_from_row!(import.account_id, row)
processed += 1
if (processed % BROADCAST_EVERY).zero?
import.update_columns(processed_rows: processed)
import.broadcast_progress
end
end
import.update_columns(processed_rows: processed, status: Import.statuses[:completed])
rescue => e
import.update_columns(status: Import.statuses[:failed], error_message: e.message)
raise
ensure
import.reload.broadcast_progress
end
end
class ImportsController < ApplicationController
def show
@import = current_account.imports.find(params[:id])
end
def create
@import = current_account.imports.new(import_params)
@import.status = :pending
if @import.save
ImportRowsJob.perform_later(@import)
redirect_to @import, notice: "Import started."
else
render :new, status: :unprocessable_entity
end
end
private
def import_params
params.require(:import).permit(:file)
end
end
<%= turbo_stream_from import %>
<div id="<%= dom_id(import, :progress) %>" class="import">
<h2>Import #<%= import.id %> — <%= import.status.titleize %></h2>
<div class="progress-bar" role="progressbar" aria-valuenow="<%= import.progress %>">
<div class="progress-bar__fill" style="width: <%= import.progress %>%"></div>
</div>
<p><%= import.processed_rows.to_i %> of <%= import.total_rows.to_i %> rows</p>
<% if import.failed? %>
<p class="error"><%= import.error_message %></p>
<% elsif import.completed? %>
<p class="done">All rows imported.</p>
<% end %>
</div>
This snippet shows how a long-running import surfaces live progress to the browser without any custom JavaScript, using Rails' Turbo Streams over Action Cable. The pattern separates durable state (a database row tracking counts) from transient UI updates (stream broadcasts), so a page reload always reflects the true progress and mid-flight updates keep the bar moving.
In Import model, progress is a plain integer derived from processed_rows and total_rows, guarded against division by zero. The key method is broadcast_progress, which calls broadcast_replace_to targeting a named stream (self) and a DOM id (dom_id(self, :progress)). Passing a partial and locals means Turbo renders the same partial used on first load, so the initial HTML and every subsequent broadcast share one source of truth. Using broadcast_replace_to (not _later) here is deliberate: the caller is already inside a background job, so an inline synchronous broadcast avoids queueing a second job just to render a partial.
In ImportRowsJob, the work loop reads a CSV and updates the record in batches. Broadcasting on every single row would flood the cable and the client; instead it throttles with processed % BROADCAST_EVERY == 0, only pushing an update every 50 rows plus one final broadcast in the ensure block. The ensure guarantees the UI settles to a terminal state (completed or failed) even if a row raises. update_columns skips validations and callbacks for the hot counter update, which matters when writing thousands of times.
In ImportsController, create persists the record and enqueues the job, then relies on the view to subscribe. The critical wiring lives in _import.html.erb: turbo_stream_from @import opens the subscription, and the inner div id must exactly match the dom_id(self, :progress) used by the broadcast, or replacements silently miss their target.
The main trade-off is throughput versus smoothness: a larger BROADCAST_EVERY reduces load but makes the bar jumpier. A subtle pitfall is forgetting that broadcasts fire from a job process, so the partial must not depend on request-specific helpers like current_user. This approach fits any job with measurable progress — imports, exports, video encodes — where users benefit from feedback but the work belongs off the request cycle.
Related snips
class CommentsController < ApplicationController
before_action :set_post
def create
@comment = @post.comments.build(comment_params)
System test: asserting Turbo Stream responses
class Post < ApplicationRecord
belongs_to :author, class_name: 'User'
has_many :comments, dependent: :destroy
scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
scope :draft, -> { where(published_at: nil) }
ActiveRecord scopes for reusable query logic
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
class PostsController < ApplicationController
def index
@posts = Post.includes(:author)
.order(created_at: :desc)
.page(params[:page])
.per(10)
Turbo Frames: infinite scroll with lazy-loading frame
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
<form data-controller="query-sync" data-action="change->query-sync#apply">
<select name="status" class="rounded border p-2">
<option value="">Any</option>
<option value="open">Open</option>
<option value="closed">Closed</option>
</select>
Filter UI that syncs query params via Stimulus (no front-end router)
Share this code
Here's the card — post it anywhere.