Performance: Image and file handling
This affects page load speed and interaction responsiveness by controlling how images and files are loaded and rendered on the page.
image_tag @user.avatar.variant(resize_to_limit: [300, 300]), loading: 'lazy', alt: 'User avatar'
image_tag @user.avatar.url, loading: 'eager'| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Eager loading full-size images | Minimal | 1 per image | High due to large decode | [X] Bad |
| Lazy loading resized images | Minimal | 1 per image | Low due to smaller decode | [OK] Good |
| Synchronous file processing on request | N/A | N/A | Blocks server response | [X] Bad |
| Asynchronous background file processing | N/A | N/A | Non-blocking | [OK] Good |
has_one_attached to link a single file to a model and has_many_attached for multiple files.has_one_attached is the correct method.attach on the attachment association, passing the file parameter.user.avatar.attach(params[:avatar]), which is the correct Rails syntax.<% if @user.avatar.attached? %>
<%= image_tag @user.avatar %>
<% else %>
<p>No avatar uploaded</p>
<% end %>attached? method returns true if a file is attached, false otherwise.def update
@user = User.find(params[:id])
@user.avatar.attach(params[:avatar])
if @user.save
redirect_to @user
else
render :edit
end
endattach method links the file to the model but does not save the model automatically.@user.save after attaching, which saves the model and the attachment together correctly.class Product < ApplicationRecord
?
end<%= form_with model: @product, local: true do |form| %>
<%= form.file_field :images, multiple: true %>
<%= form.submit %>
<% end %>has_many_attached in the model.multiple: true on file_field, which pairs with has_many_attached.Pass the test and this pattern moves unknown