Performance: File uploads with Active Storage
This affects page load speed and interaction responsiveness during file uploads and downloads.
class DocumentsController < ApplicationController def new @document = Document.new end def create @document = Document.new(document_params) if @document.save redirect_to @document else render :new end end private def document_params params.require(:document).permit(:title, :file) end end # In the form view: <%= form_with model: @document, local: false do |form| %> <%= form.text_field :title %> <%= form.file_field :file, direct_upload: true %> <%= form.submit %> <% end %>
class DocumentsController < ApplicationController def create @document = Document.new(document_params) if @document.save redirect_to @document else render :new end end private def document_params params.require(:document).permit(:title, :file) end end
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Uploading files through Rails server | Minimal DOM changes | 0 | 0 | [!] OK but server load increases |
| Direct uploads with Active Storage | Minimal DOM changes | 0 | 0 | [OK] Efficient and scalable |
has_one_attached in a Rails model when using Active Storage?has_one_attached macro in a Rails model declares a one-to-one association between the model and a single uploaded file.file_field helper creates a file input allowing users to select files for upload.class User < ApplicationRecord has_one_attached :profile_pic end # In the form view: <%= form_with model: @user do |form| %> <%= form.file_field :profile_pic %> <%= form.submit %> <% end %>
has_one_attached :profile_pic, so it can attach one file to the user.form_with, so the file will be sent correctly.class Product < ApplicationRecord has_one_attached :images end # In the form: <%= form.file_field :images, multiple: true %>
has_one_attached, which supports only one file, but the form allows multiple files.has_many_attached.has_many_attached :photos in the model.file_field :photos, multiple: true to allow selecting multiple files.@model.photos to show thumbnails.Pass the test and this pattern moves unknown