Reputation: 1201
I'm trying out ActiveStorage for the first time and wondering what the convention is for controller code used to purge some or all of a resource's attached files?
Two solutions I can see, and hate:
destroy
methodsWhat is the Rails way of handling edits made to a resource's ActiveStorage attachment(s)?
Upvotes: 3
Views: 149
Reputation: 26535
I’d choose the first solution you considered:
A designated controller just for managing attachments (which would omit any kind of resource specific callbacks
This is roughly what we do in Basecamp. Here’s a demo:
# app/models/event.rb
class Event < ApplicationRecord
belongs_to :user
has_many_attached :highlights
end
# app/controllers/events/highlights_controller.rb
class Events::HighlightsController < ApplicationController
before_action :set_event, :set_highlight
def destroy
@highlight.purge_later
redirect_to @event
end
private
def set_event
@event = Current.user.events.find(params[:event_id])
end
def set_highlight
@highlight = @event.highlights.find(params[:id])
end
end
# config/routes.rb
Rails.application.routes.draw do
resources :events do
resources :highlights, controller: "events/highlights"
end
end
<%# app/views/events/show.html.erb %>
<% @event.highlights.each do |highlight| %>
<%= link_to image_tag(highlight.representation(resize: "200x200>")), highlight %><br>
<%= link_to "Delete this highlight", event_highlight_path(@event, highlight), method: :delete %>
<% end %>
Upvotes: 1