Module: Koi::Controller::HasAttachments

Extended by:
ActiveSupport::Concern
Defined in:
app/controllers/concerns/koi/controller/has_attachments.rb

Instance Method Summary collapse

Instance Method Details

#save_attachments!(resource) ⇒ Object

Store attachments in the given object so that they can be preserved for the next form submission.

Example:

def create
  @document = Document.new(document_params)
  if @document.save
    redirect_to [:admin, @document], status: :see_other
  else
    store_attachments(@document)
    render :new, status: :unprocessable_content
  end
end

Parameters:

  • resource (ActiveRecord::Base)

    The object being edited



23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/controllers/concerns/koi/controller/has_attachments.rb', line 23

def save_attachments!(resource)
  resource.attachment_changes.each_value do |change|
    case change
    when ActiveStorage::Attached::Changes::CreateOne
      change.upload
      change.blob.save!
    when ActiveStorage::Attached::Changes::CreateMany
      change.upload
      change.blobs.each(&:save!)
    end
  end
end