ruby erb 93 lines · 4 tabs

Broadcast job progress updates to a Turbo Frame

Shared by codesnips Jan 2026
4 tabs
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
4 files · ruby, erb Explain with highlit

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

ruby
class CommentsController < ApplicationController
  before_action :set_post

  def create
    @comment = @post.comments.build(comment_params)

System test: asserting Turbo Stream responses

rails hotwire turbo
by codesnips 4 tabs
ruby
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

rails activerecord patterns
by Alex Kumar 1 tab
ruby
module Api
  module V1
    class UsersController < BaseController
      def show
        user = User.includes(:profile).find(params[:id])

ETags for conditional requests and caching

rails caching http-caching
by Alex Kumar 1 tab
ruby
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

rails turbo hotwire
by codesnips 4 tabs
ruby
require "csv"

class PeopleCsvStream
  include Enumerable

  HEADERS = %w[id full_name email signed_up_at plan].freeze

Resilient CSV Export as a Streamed Response

rails performance streaming
by codesnips 3 tabs
erb
<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)

rails hotwire stimulus
by Henry Kim 2 tabs

Share this code

Here's the card — post it anywhere.

Broadcast job progress updates to a Turbo Frame — share card
Link copied