Support file uploads

This allows submissions to store file uploads
This commit is contained in:
2020-04-09 11:02:07 +02:00
parent 73ccddee94
commit 10d80c6548
9 changed files with 107 additions and 14 deletions

View File

@@ -1,17 +1,20 @@
class Submission < ApplicationRecord
belongs_to :form
after_create :append_to_spreadsheet
validates_presence_of :data
has_many :file_uploads, dependent: :destroy
has_many_attached :files
def data=(value)
sanitized_data = {}
value.each do |key, value|
sanitized_data[key] = submission_value(value)
validates_presence_of :data, if: :appended_at?
def process_data(submitted_data)
processed_data = {}
submitted_data.each do |key, value|
processed_data[key] = submission_value_for(value)
end
write_attribute(:data, sanitized_data)
update_attribute(:data, processed_data)
SubmissionAppendJob.perform_later(self.id)
end
def submission_value(value)
def submission_value_for(value)
case value
when Array
value.join(', ')
@@ -20,7 +23,16 @@ class Submission < ApplicationRecord
when 'tinyforms_now'
Time.now.utc.to_formatted_s(:rfc822)
when ActionDispatch::Http::UploadedFile
''
# manually create the ActiveStorage attachment because we need the ID of the Attachment to create the URL
# first the file needs to be uplaoded then we can create an Attachment
# The CreateOne mainly handles the uplaod and the creation of the blob for us
# `files` is the name from `has_many_attached :files`
create_one = ActiveStorage::Attached::Changes::CreateOne.new('files', self, value)
create_one.upload
attachment = ActiveStorage::Attachment.new(record: self, name: 'files', blob: create_one.blob)
attachment.save
# return the URL that we use to show in the Spreadsheet
Rails.application.routes.url_helpers.file_upload_url(form_id: form, submission_id: self, id: attachment.id, host: DEFAULT_HOST)
else
value.to_s
end