Bird
Raised Fist0
Ruby on Railsframework~10 mins

File uploads with Active Storage in Ruby on Rails - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - File uploads with Active Storage
User selects file in form
↓
Form submits file data
↓
Rails controller receives file
↓
Active Storage attaches file to model
↓
File saved to storage service
↓
Model now has attached file reference
↓
File can be displayed or downloaded
This flow shows how a user uploads a file through a form, Rails receives it, Active Storage attaches it to a model, and saves it to storage.
Execution Sample
Ruby on Rails
class User < ApplicationRecord
  has_one_attached :avatar
end

# In controller:
@user.avatar.attach(params[:avatar])
This code attaches an uploaded file from params to the user's avatar using Active Storage.
Execution Table
StepActionInput/StateResult/State Change
1User selects file in formFile chosen: avatar.pngFile data ready to send
2Form submitsHTTP POST with file dataServer receives file in params[:avatar]
3Controller calls attach@user.avatar.attach(params[:avatar])Active Storage prepares attachment
4Active Storage saves fileFile data stored in configured serviceBlob record created, file saved
5Model updated@user.avatar attachedUser model now references uploaded file
6File accessibleUser.avatar attachedFile can be displayed or downloaded
7EndAll steps completeUpload process finished
💡 Upload completes when file is saved and attached to model
Variable Tracker
VariableStartAfter Step 3After Step 4Final
params[:avatar]nilFile data (avatar.png)File data storedFile data stored
@user.avatar.attached?falsetruetruetrue
ActiveStorage::Blobnonependingcreatedcreated
Key Moments - 3 Insights
Why does @user.avatar.attached? return false before attach?
Because the file is not yet attached to the user model until attach is called (see execution_table step 3).
What happens if no file is selected in the form?
params[:avatar] will be nil, so attach is not called and no file is saved (no change in variable_tracker).
How does Active Storage know where to save the file?
It uses the configured storage service (local, cloud) set in Rails config, as shown in step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step does the file become attached to the user model?
AStep 3
BStep 2
CStep 5
DStep 1
💡 Hint
Check the 'Result/State Change' column for when '@user.avatar attached' appears.
According to variable_tracker, what is the value of @user.avatar.attached? after step 4?
Afalse
Btrue
Cnil
Dpending
💡 Hint
Look at the '@user.avatar.attached?' row under 'After Step 4' column.
If the user does not select a file, what will params[:avatar] be at step 2?
Anil
BFile data
CEmpty string
DError
💡 Hint
Refer to key_moments about what happens if no file is selected.
Concept Snapshot
File uploads with Active Storage in Rails:
- Add 'has_one_attached :file' to model
- Use form with file_field for upload
- In controller, call 'model.file.attach(params[:file])'
- Active Storage saves file to configured service
- Access file via 'model.file' methods
- Check attachment with 'attached?' method
Full Transcript
This visual execution trace shows how file uploads work with Active Storage in Rails. The user selects a file in a form, which submits the file data to the server. The Rails controller receives the file in params and calls attach on the model's attachment. Active Storage then saves the file to the configured storage service and updates the model to reference the file. The variable tracker shows how params and attachment state change step-by-step. Key moments clarify common confusions like when the file is considered attached and what happens if no file is selected. The quiz tests understanding of these steps and states. This helps beginners see the full upload process clearly.

Practice

(1/5)
1. What is the purpose of has_one_attached in a Rails model when using Active Storage?
easy
A. To link a single uploaded file to a model instance
B. To create a database table for storing files
C. To validate the file type before upload
D. To automatically resize uploaded images

Solution

  1. Step 1: Understand Active Storage attachment macros

    The has_one_attached macro in a Rails model declares a one-to-one association between the model and a single uploaded file.
  2. Step 2: Differentiate from other options

    It does not create tables, validate file types, or resize images by itself; those are handled elsewhere.
  3. Final Answer:

    To link a single uploaded file to a model instance -> Option A
  4. Quick Check:

    has_one_attached = single file link [OK]
Hint: Remember: has_one_attached means one file per model [OK]
Common Mistakes:
  • Confusing has_one_attached with database table creation
  • Thinking it validates or processes files automatically
  • Mixing it up with has_many_attached for multiple files
2. Which of the following is the correct way to add a file input field in a Rails form for uploading a file with Active Storage?
easy
A. <%= form.file_field :avatar %>
B. <%= form.text_field :avatar %>
C. <%= form.submit :avatar %>
D. <%= form.select :avatar %>

Solution

  1. Step 1: Identify the correct form helper for file uploads

    The file_field helper creates a file input allowing users to select files for upload.
  2. Step 2: Exclude other input types

    Text fields, submit buttons, and select dropdowns do not allow file selection.
  3. Final Answer:

    <%= form.file_field :avatar %> -> Option A
  4. Quick Check:

    file_field = file input [OK]
Hint: Use file_field for file inputs in forms [OK]
Common Mistakes:
  • Using text_field instead of file_field for uploads
  • Confusing submit button with file input
  • Using select dropdown for file selection
3. Given the following model and form code, what will be the result after submitting a file?
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 %>
medium
A. The file will be ignored because has_one_attached is missing
B. The uploaded file will be attached to the user's profile_pic
C. The form will raise a syntax error due to missing multipart option
D. The file will be saved as a string in the profile_pic column

Solution

  1. Step 1: Check model attachment declaration

    The model uses has_one_attached :profile_pic, so it can attach one file to the user.
  2. Step 2: Understand form_with default behavior

    Rails 6+ automatically sets multipart for file uploads in form_with, so the file will be sent correctly.
  3. Final Answer:

    The uploaded file will be attached to the user's profile_pic -> Option B
  4. Quick Check:

    has_one_attached + file_field = file attached [OK]
Hint: form_with sets multipart automatically for file_field [OK]
Common Mistakes:
  • Assuming file is saved as string in DB column
  • Thinking multipart option must be manually added
  • Believing file is ignored without extra code
4. Identify the error in this code snippet for attaching multiple files using Active Storage:
class Product < ApplicationRecord
  has_one_attached :images
end

# In the form:
<%= form.file_field :images, multiple: true %>
medium
A. The model should not declare any attachment for multiple files
B. file_field does not support the multiple option
C. The form must use text_field instead of file_field
D. has_one_attached should be has_many_attached for multiple files

Solution

  1. Step 1: Check model attachment type

    The model uses has_one_attached, which supports only one file, but the form allows multiple files.
  2. Step 2: Correct attachment macro for multiple files

    To attach multiple files, the model must use has_many_attached.
  3. Final Answer:

    has_one_attached should be has_many_attached for multiple files -> Option D
  4. Quick Check:

    Multiple files need has_many_attached [OK]
Hint: Use has_many_attached for multiple file uploads [OK]
Common Mistakes:
  • Using has_one_attached with multiple: true
  • Thinking file_field can't handle multiple files
  • Not declaring attachment in model for uploads
5. You want to allow users to upload multiple images for a gallery and display thumbnails after upload. Which combination of model and view code correctly implements this with Active Storage?
hard
A. Model: has_many_attached :photos
View: form.text_field :photos
B. Model: has_one_attached :photos
View: form.file_field :photos
C. Model: has_many_attached :photos
View: form.file_field :photos, multiple: true
D. Model: has_one_attached :photos
View: form.file_field :photos, multiple: true

Solution

  1. Step 1: Choose correct model attachment for multiple files

    To attach multiple images, use has_many_attached :photos in the model.
  2. Step 2: Use file_field with multiple option in the form

    The form must use file_field :photos, multiple: true to allow selecting multiple files.
  3. Step 3: Display thumbnails after upload

    With this setup, you can iterate over @model.photos to show thumbnails.
  4. Final Answer:

    Model: has_many_attached :photos and View: form.file_field :photos, multiple: true -> Option C
  5. Quick Check:

    Multiple files need has_many_attached + multiple: true [OK]
Hint: Multiple files = has_many_attached + file_field multiple: true [OK]
Common Mistakes:
  • Using has_one_attached for multiple files
  • Omitting multiple: true in file_field
  • Using text_field instead of file_field for uploads
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard