ActiveStorage and Direct Uploading

Correct. Which is why the direct upload example includes the code necessary to create a loading bar so that the user has some feedback on how much of the file has been uploaded.

And yes, as long as you use rails defaults, everything will be handled automatically in the controller. For example:

class Photo
  has_one_attached :file
end
<%= form_with @photo do |form| %>
  <%= form.file_field :file, direct_upload: true %>
  <%= form.submit %>
<% end %>
  def new
    @photo = Photo.new
  end

  def create
    @photo = Photo.new(photo_params)

    if @photo.save
      redirect_to @photo
    else
      render "new", status: :unprocessable_entity
    end
  end

  private
    def photo_params
      require(:photo).permit(:file)
    end

This should be everything for a minimalistic direct upload. The JS file will create a hidden field called file with the identifier for the uploaded file, and the controller will automatically attach the file when it notices that an identifier has been set to the file attribute of Photo which is a has_one_attached.

And you probably want to enqueue your job inside the if @photo.save, just before the redirect_to

2 Likes