Class: Avo::AttachmentsController

Inherits:
ApplicationController
  • Object
show all
Defined in:
app/controllers/avo/attachments_controller.rb

Instance Method Summary collapse

Instance Method Details

#createObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'app/controllers/avo/attachments_controller.rb', line 7

def create
  association_name = BaseResource.valid_attachment_name(@record, params[:attachment_key])

  if association_name
    return render_upload_unauthorized unless authorized_to_upload(association_name)

    blob = ActiveStorage::Blob.create_and_upload! io: params[:file].to_io, filename: params[:filename]
    @record.send(association_name).attach blob
  elsif params[:key].present?
    return render_upload_unauthorized unless authorized_to_trix_upload?

    blob = ActiveStorage::Blob.create_and_upload! io: params[:file].to_io, filename: params[:filename]
  else
    raise ActionController::BadRequest.new("Could not find the attachment association for #{params[:attachment_key]} (check the `attachment_key` for this Trix field)")
  end

  render json: {
    url: main_app.url_for(blob),
    href: main_app.url_for(blob)
  }
end

#destroyObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'app/controllers/avo/attachments_controller.rb', line 29

def destroy
  if authorized_to :delete
    attachment = ActiveStorage::Attachment.find(params[:attachment_id])

    if attachment.present?
      ActiveRecord::Base.transaction do
        @destroyed = attachment
        attachment.destroy!
        @record.reload
        unless @record.save
          @destroyed = nil
          raise ActiveRecord::Rollback
        end
      end

      if @destroyed.present?
        flash[:notice] = t("avo.attachment_destroyed")
      else
        flash[:error] = @record.errors.full_messages.join(", ")
      end
    else
      t("avo.failed_to_find_attachment")
    end
  else
    flash[:notice] = t("avo.not_authorized")
  end

  respond_to do |format|
    format.turbo_stream do
      render "destroy"
    end
  end
end