erb javascript ruby 95 lines · 3 tabs

Active Storage direct upload progress with Stimulus

Shared by codesnips Jan 2026
3 tabs
<%= form_with model: @document, data: { controller: "upload" } do |form| %>
  <div class="field">
    <%= form.label :file, "Attach a document" %>
    <%= form.file_field :file,
          direct_upload: true,
          data: { upload_target: "input" } %>
  </div>

  <div class="progress" data-upload-target="progress" hidden>
    <div class="progress__bar"
         data-upload-target="bar"
         role="progressbar"
         aria-valuemin="0"
         aria-valuemax="100"
         aria-valuenow="0"></div>
    <span class="progress__label" data-upload-target="label">0%</span>
  </div>

  <%= form.submit "Save", data: { upload_target: "submit" } %>
<% end %>
3 files · erb, javascript, ruby Explain with highlit

This snippet shows how to give an Active Storage direct upload a real progress bar driven entirely on the client with a Stimulus controller, without waiting for a full server round trip. Active Storage's DirectUpload object streams the file straight to the storage service (S3, GCS, or disk) and only submits the resulting signed_id with the form, so the browser knows the exact byte progress before Rails ever sees the request. The trick is to hook into that upload lifecycle and reflect it in the DOM.

The _form.html.erb tab wires everything up declaratively. The file_field is rendered with direct_upload: true, which makes Rails include the activestorage JS that dispatches direct-upload events. The surrounding div carries data-controller="upload" and the progress markup carries data-upload-target attributes, so the Stimulus controller can find the bar and label without any manual querySelector calls. Disabling the submit button up front prevents a user from posting the form while bytes are still in flight.

The upload_controller.js tab is the core. Active Storage emits four events on the <input> element: direct-upload:initialize, :start, :progress, and :end. The controller listens for them in connect() and tears the listeners down in disconnect() to avoid leaks when Turbo swaps the DOM. The progress handler reads event.detail.progress (a 0-100 float) and writes it to the bar's style.width and aria-valuenow, keeping the UI accessible. On :end it re-enables the submit button.

A subtle point: each file gets its own event because event.detail.id correlates the DOM data-direct-upload-id element that Active Storage injects, so multiple files can report independent progress. The direct-upload:error case is handled by surfacing event.detail.error and preventing default so Rails doesn't silently drop the failure.

The DocumentsController tab closes the loop: because the upload already happened, the controller simply calls document.file.attach(params.dig(:document, :file)) with the signed_id, which is a cheap metadata write rather than a file transfer. This pattern keeps large uploads responsive, offloads bandwidth from the app server, and gives users honest feedback, at the cost of relying on client JS and correctly configured CORS on the bucket.


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.

Active Storage direct upload progress with Stimulus — share card
Link copied