Complete the code to attach an image file to a Rails model using Active Storage.
class User < ApplicationRecord has_one_attached :[1] end
The has_one_attached method defines a one-to-one attachment for the model. Here, avatar is the common name used for user profile images.
Complete the code to permit the image attachment parameter in a Rails controller.
def user_params params.require(:user).permit(:name, [1]) end
To allow file uploads, the attachment name (here :avatar) must be permitted in strong parameters.
Fix the error in the view code to display the attached image if it exists.
<% if @user.[1].attached? %> <%= image_tag @user.avatar %> <% end %>
attached? on the model instead of the attachment.The method attached? checks if the named attachment exists. It must match the attachment name defined in the model.
Fill both blanks to create a variant of the attached image resized to 100x100 pixels.
<%= image_tag @user.avatar.variant([1]: [2]) %>
resize_to_fill crops the image, which may not be desired.The variant method creates a resized version of the image. resize_to_limit resizes the image to fit within the given dimensions without cropping.
Fill all three blanks to create a hash of filenames and their byte sizes for all attached files.
files_info = @document.files.each_with_object({}) do |file, hash|
hash[[1]] = file.blob.[2]
end
files_info.keys.first == [3]file.filename directly as a hash key causes issues because it is not a string.size instead of byte_size returns nil.To get the filename as a string, use file.filename.to_s. The file size in bytes is accessed with blob.byte_size.