tinyforms/app/models/submission.rb

51 lines
1.7 KiB
Ruby

class Submission < ApplicationRecord
belongs_to :form
has_many_attached :files
acts_as_sequenced scope: :form_id
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
update_attribute(:data, processed_data)
SubmissionAppendJob.perform_later(self.id)
end
def submission_value_for(value)
case value
when Array
value.join(', ')
when Hash
JSON.dump(value)
when 'tinyforms_now'
Time.now.utc.to_formatted_s(:rfc822)
when 'tinyforms_token'
form.token
when 'tinyforms_id'
sequential_id
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
end
def append_to_spreadsheet
result = form.append(data)
update_column(:appended_at, Time.current) if result.updates.updated_rows > 0
end
end