Bird
Raised Fist0
Ruby on Railsframework~10 mins

Image and file handling in Ruby on Rails - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Image and file handling
User uploads file
↓
Rails receives file in params
↓
Attach file to model using Active Storage
↓
File saved in storage service
↓
File accessible via URL or download
↓
Display or process file in views/controllers
This flow shows how Rails handles user file uploads by receiving the file, attaching it to a model with Active Storage, saving it, and then making it accessible for display or download.
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 avatar image file to a User model instance using Active Storage.
Execution Table
StepActionInput/StateResult/State Change
1User submits form with fileparams[:avatar] = uploaded fileFile data received in params
2Controller calls attach@user.avatar.attach(params[:avatar])File attached to @user's avatar
3Active Storage saves fileFile attachedFile saved in configured storage (local/cloud)
4File metadata savedAttachment infoDatabase records created for attachment
5File accessible via URL@user.avatarURL generated for file access
6View renders image tag<%= image_tag @user.avatar %>Image displayed in browser
7User requests file downloadURL accessedFile served from storage
8File deleted if detached@user.avatar.purgeFile removed from storage and DB
9EndNo further actionProcess complete
💡 File is saved and accessible until explicitly removed or model is destroyed
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
params[:avatar]niluploaded file objectuploaded file objectuploaded file objectuploaded file object
@user.avatar.attached?falsetruetruetruetrue
Storage file presencenonenonefile savedfile savedfile saved
DB attachment recordnonenonenonecreatedcreated
Key Moments - 3 Insights
Why does the file not appear immediately after attach is called?
Because attach queues the file to be saved, but the actual file saving happens asynchronously or after the request completes, as shown in steps 2 and 3 of the execution_table.
What happens if you call purge on the attachment?
Calling purge removes the file from storage and deletes the attachment record from the database, as shown in step 8 of the execution_table.
How does Rails know where to save the file?
Rails uses the configured Active Storage service (local disk, Amazon S3, etc.) defined in config/storage.yml, which is referenced during the file save step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step is the file actually saved to storage?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Check the 'Result/State Change' column for when the file is saved in storage.
According to variable_tracker, when does @user.avatar.attached? become true?
AAfter Step 1
BAfter Step 3
CAfter Step 2
DAfter Step 4
💡 Hint
Look at the @user.avatar.attached? row and see when it changes from false to true.
If you remove the file using purge, which step in execution_table shows this action?
AStep 8
BStep 6
CStep 7
DStep 9
💡 Hint
Look for the step mentioning file deletion or purge.
Concept Snapshot
Rails Image and File Handling with Active Storage:
- Use has_one_attached or has_many_attached in models
- Attach files via model_instance.attach(params[:file])
- Files saved in configured storage (local/cloud)
- Access files with model_instance.file
- Remove files with model_instance.file.purge
- Display files in views with image_tag or link_to
Full Transcript
In Rails, image and file handling is done using Active Storage. When a user uploads a file, it is received in the controller through params. The file is then attached to a model instance using the attach method. Active Storage saves the file in the configured storage service, such as local disk or cloud storage. Metadata about the attachment is saved in the database. The file can be accessed via URLs generated by Active Storage and displayed in views using helpers like image_tag. Files can be deleted by calling purge on the attachment. This process ensures files are managed efficiently and securely within Rails applications.

Practice

(1/5)
1. Which method in Rails is used to associate a single file attachment with a model?
easy
A. has_many_attached
B. has_one_attached
C. attach_file
D. file_attachment

Solution

  1. Step 1: Understand Rails Active Storage associations

    Rails uses has_one_attached to link a single file to a model and has_many_attached for multiple files.
  2. Step 2: Identify the correct method for single file

    Since the question asks for a single file, has_one_attached is the correct method.
  3. Final Answer:

    has_one_attached -> Option B
  4. Quick Check:

    Single file attachment = has_one_attached [OK]
Hint: Single file uses has_one_attached, multiple files use has_many_attached [OK]
Common Mistakes:
  • Confusing has_one_attached with has_many_attached
  • Using non-existent methods like attach_file
  • Thinking file_attachment is a Rails method
2. Which of the following is the correct syntax to attach a file to a model instance in a Rails controller?
easy
A. user.avatar.attach(params[:avatar])
B. user.attach_avatar(params[:avatar])
C. user.avatar = params[:avatar]
D. user.attach_file(:avatar, params[:avatar])

Solution

  1. Step 1: Recall the Active Storage attach syntax

    To attach a file, you call attach on the attachment association, passing the file parameter.
  2. Step 2: Match the syntax to the options

    user.avatar.attach(params[:avatar]) uses user.avatar.attach(params[:avatar]), which is the correct Rails syntax.
  3. Final Answer:

    user.avatar.attach(params[:avatar]) -> Option A
  4. Quick Check:

    Attach file with .attach method on association [OK]
Hint: Use .attach on the attachment association to add files [OK]
Common Mistakes:
  • Using non-existent methods like attach_avatar
  • Assigning file directly to association
  • Trying to call attach_file which is not a Rails method
3. Given the following code in a Rails view:
<% if @user.avatar.attached? %>
  <%= image_tag @user.avatar %>
<% else %>
  <p>No avatar uploaded</p>
<% end %>

What will be displayed if the user has not uploaded an avatar?
medium
A. An error because avatar is nil
B. The image tag with a broken image
C. The text 'No avatar uploaded'
D. Nothing will be displayed

Solution

  1. Step 1: Understand the attached? method

    The attached? method returns true if a file is attached, false otherwise.
  2. Step 2: Analyze the conditional rendering

    If no avatar is attached, the else block runs, showing the text 'No avatar uploaded'.
  3. Final Answer:

    The text 'No avatar uploaded' -> Option C
  4. Quick Check:

    attached? false shows else text [OK]
Hint: Check attached? before showing file to avoid errors [OK]
Common Mistakes:
  • Assuming image_tag works with nil attachment
  • Expecting no output instead of else block
  • Confusing attached? with presence of file path
4. Consider this controller code snippet:
def update
  @user = User.find(params[:id])
  @user.avatar.attach(params[:avatar])
  if @user.save
    redirect_to @user
  else
    render :edit
  end
end

What is the main issue with this code when attaching a file?
medium
A. Using attach before save causes an error
B. params[:avatar] should be inside a hash like avatar: params[:avatar]
C. attach should be called only after @user.save
D. attach does not save the file automatically

Solution

  1. Step 1: Understand attach behavior

    The attach method links the file to the model but does not save the model automatically.
  2. Step 2: Analyze the save call

    The code calls @user.save after attaching, which saves the model and the attachment together correctly.
  3. Step 3: Identify the issue

    attach does not save the file automatically correctly states that attach alone does not save the file; save must be called to persist changes.
  4. Final Answer:

    attach does not save the file automatically -> Option D
  5. Quick Check:

    attach links file, save persists it [OK]
Hint: Remember to call save after attach to persist files [OK]
Common Mistakes:
  • Thinking attach saves file immediately
  • Calling attach after save instead of before
  • Passing params incorrectly to attach
5. You want to allow users to upload multiple images for a product in Rails. Which combination of model and view code correctly supports this?

Model:
class Product < ApplicationRecord
  ?
end

View form snippet:
<%= form_with model: @product, local: true do |form| %>
  <%= form.file_field :images, multiple: true %>
  <%= form.submit %>
<% end %>
hard
A. Model: has_many_attached :images
B. Model: has_one_attached :images
C. Model: has_many :images
D. Model: has_one :images

Solution

  1. Step 1: Identify multiple file attachment method

    For multiple files, Rails uses has_many_attached in the model.
  2. Step 2: Match with form file_field multiple option

    The form uses multiple: true on file_field, which pairs with has_many_attached.
  3. Final Answer:

    Model: has_many_attached :images -> Option A
  4. Quick Check:

    Multiple files need has_many_attached [OK]
Hint: Use has_many_attached with multiple: true in file_field [OK]
Common Mistakes:
  • Using has_one_attached for multiple files
  • Confusing has_many association with Active Storage
  • Not setting multiple: true in the form
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