3

Has anyone created a form where a user can remove their previously uploaded images from Active Storage and Amazon S3 by clicking a button? I used the question here as a guide but my app is set up a bit differently. The images are saved as an array (see controller params).

The form renders the delete button and images but when the delete button is clicked I get an error "Couldn't find Space with 'id'=eyJfcmFpbHM..." and this line in my set_space method is highlighted

@space = Space.find(params[:id])

Here is the relevant code

The controller

class SpacesController < ApplicationController
  before_action :set_space, except: [:index, :new, :create]
  before_action :authenticate_user!, except: [:show]


  def update
    if @space.update(space_params)
      flash[:notice] = "Saved!"
    else
      flash[:notice] = "Something went wrong. Please check your submission and try again."
    end
      redirect_back(fallback_location: request.referer)
  end


  def delete_image_attachment
    @space_image = ActiveStorage::Blob.find_signed(params[:id])
    @space_image.purge_later
    redirect_to listing_space_path(@space)
  end

  private
    def set_space
      @space = Space.find(params[:id])
    end

    def space_params
        params.require(:space).permit(:space_name, :space_type, :description, space_image: [])
    end

end

The view with the delete button/ icon

<div>
  <% if @space.image.attached? %>
      <% @space.image.each do |image| %>
      <%= image_tag image %>
      <span>
        <%= link_to '<- Remove', delete_image_attachment_space_url(image.signed_id),
                method: :delete,
                data: { confirm: 'Are you sure?' } %>
        <i class="fas fa-trash"></i>
      </span>
    <% end %>
  <% end %>
</div>

Routes.rb

resources :spaces, except: [:edit] do
  member do
    get 'listing'
    delete :delete_image_attachment
  end
end
Erin B.
  • 165
  • 3
  • 15

1 Answers1

2

set_space is looking for an id of a Space object

The call to delete_image_attachment is passing image.signed_id, the id for the SpaceImage object, not the id for the Space object.

Assuming the navigation has been set up in a standard manner on the Space and SpaceImage classes, the space object can be found from an image object. So make these changes...

before_action :set_space, except: [:index, :new, :create, :delete_image_attachment]

def delete_image_attachment
  @space_image = ActiveStorage::Blob.find_signed(params[:id])
  @space_image.purge_later
  redirect_to listing_space_path(@space_image.space)
end

That will pass the proper space id to the listing_space_path.

dbugger
  • 15,868
  • 9
  • 31
  • 33