tinyforms/app/models/form.rb

73 lines
1.5 KiB
Ruby

class Form < ApplicationRecord
belongs_to :user
has_many :submissions, dependent: :destroy
before_validation :insert_defaults, on: :create
after_create :create_spreadsheet
has_secure_token
encrypts :airtable_api_key
encrypts :airtable_app_key
validates_presence_of :title
validates_inclusion_of :backend_name, in: ['google_sheets', 'airtable']
# Airtable validations
validates_presence_of :airtable_api_key, if: :airtable?
validates_presence_of :airtable_app_key, if: :airtable?
validates_presence_of :airtable_table, if: :airtable?
# TODO: use counter_cache option on association
def submissions_count
@submissions_count ||= submissions.count
end
def last_submission_date
@last_submission_date ||= submissions.order(created_at: :desc).first&.created_at
end
def deactivate!(reason = nil)
self.user.deactivate!(reason)
end
def active?
self.user.active?
end
def airtable?
backend_name == 'airtable'
end
def google
backend_name == 'google'
end
def backend
@backend ||= SpreadsheetBackends.const_get(backend_name.camelize).new(self)
end
def spreadsheet_url
backend.url
end
def create_spreadsheet
backend.create
end
def append_to_spreadsheet(data)
backend.append(data)
end
def spreadsheet_headers
backend.headers
end
def to_param
token
end
def insert_defaults
self.backend_name ||= airtable_app_key.present? ? 'airtable' : 'google_sheets'
end
end