0
0
Ruby on Railsframework~10 mins

Image and file handling in Ruby on Rails - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to attach an image file to a Rails model using Active Storage.

Ruby on Rails
class User < ApplicationRecord
  has_one_attached :[1]
end
Drag options to blanks, or click blank then click option'
Aphoto
Bimage
Cavatar
Dfile
Attempts:
3 left
💡 Hint
Common Mistakes
Using plural form like 'avatars' instead of singular 'avatar'.
Using generic names like 'file' which are less descriptive.
2fill in blank
medium

Complete the code to permit the image attachment parameter in a Rails controller.

Ruby on Rails
def user_params
  params.require(:user).permit(:name, [1])
end
Drag options to blanks, or click blank then click option'
A:avatar
B:image
C:photo
D:file
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to permit the attachment parameter causes the file not to be saved.
Using string instead of symbol for the parameter.
3fill in blank
hard

Fix the error in the view code to display the attached image if it exists.

Ruby on Rails
<% if @user.[1].attached? %>
  <%= image_tag @user.avatar %>
<% end %>
Drag options to blanks, or click blank then click option'
Aavatar
Bimage
Cphoto
Dfile
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different attachment name causes a runtime error.
Calling attached? on the model instead of the attachment.
4fill in blank
hard

Fill both blanks to create a variant of the attached image resized to 100x100 pixels.

Ruby on Rails
<%= image_tag @user.avatar.variant([1]: [2]) %>
Drag options to blanks, or click blank then click option'
Aresize_to_limit
B[100, 100]
C[200, 200]
Dresize_to_fill
Attempts:
3 left
💡 Hint
Common Mistakes
Using resize_to_fill crops the image, which may not be desired.
Passing size as a string instead of an array.
5fill in blank
hard

Fill all three blanks to create a hash of filenames and their byte sizes for all attached files.

Ruby on Rails
files_info = @document.files.each_with_object({}) do |file, hash|
  hash[[1]] = file.blob.[2]
end

files_info.keys.first == [3]
Drag options to blanks, or click blank then click option'
Afile.filename.to_s
Bbyte_size
Cfile.filename
Dsize
Attempts:
3 left
💡 Hint
Common Mistakes
Using file.filename directly as a hash key causes issues because it is not a string.
Using size instead of byte_size returns nil.