Challenge - 5 Problems
Active Storage Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediateWhat happens when you attach a file using Active Storage?
Consider a Rails model
User with has_one_attached :avatar. What is the behavior after running user.avatar.attach(io: File.open('path/to/file.jpg'), filename: 'file.jpg') and saving the user?Attempts:
2 left
💡 Hint
Think about how Active Storage separates file data from model data.
✗ Incorrect
Active Storage uploads the file to the configured storage service and creates a record linking the file to the model. The file is not stored inside the database record itself.
📝 Syntax
intermediateWhich code correctly attaches multiple files to a model using Active Storage?
Given a model
Post with has_many_attached :images, which option correctly attaches two image files to a post?Attempts:
2 left
💡 Hint
Check the syntax for attaching multiple files as an array of hashes.
✗ Incorrect
To attach multiple files, you pass an array of hashes with io and filename keys to attach.
🔧 Debug
advancedWhy does this Active Storage file upload raise an error?
Given the code snippet:
What error will this cause and why?
user.avatar.attach(io: 'path/to/file.jpg', filename: 'file.jpg')
What error will this cause and why?
Ruby on Rails
user.avatar.attach(io: 'path/to/file.jpg', filename: 'file.jpg')
Attempts:
2 left
💡 Hint
Check the type expected for the
io parameter.✗ Incorrect
The io parameter must be an IO object like a File or StringIO. Passing a string path directly causes a TypeError.
❓ state_output
advancedWhat is the value of
user.avatar.attached? after attaching and saving?Given a
What does
User model with has_one_attached :avatar, after running:user.avatar.attach(io: File.open('avatar.png'), filename: 'avatar.png')
user.saveWhat does
user.avatar.attached? return?Attempts:
2 left
💡 Hint
Check the method that tells if a file is attached.
✗ Incorrect
The attached? method returns true if a file is linked to the attachment.
🧠 Conceptual
expertHow does Active Storage handle file deletion when a model is destroyed?
When a model with attached files is destroyed, what happens to the files stored by Active Storage?
Attempts:
2 left
💡 Hint
Think about how Active Storage manages cleanup of attachments.
✗ Incorrect
Active Storage automatically deletes files from the storage service when the associated record is destroyed.
