Store AJAX uploaded documents with timestamp prefix to avoid file name collision. Remove cached_attachments after document save.

This commit is contained in:
Senén Rodero Rodríguez
2017-08-24 18:15:43 +02:00
parent 2e1d98c408
commit f4ac8b17d0
2 changed files with 31 additions and 22 deletions

View File

@@ -20,28 +20,36 @@ class Document < ActiveRecord::Base
validates :documentable_id, presence: true, if: -> { persisted? }
validates :documentable_type, presence: true, if: -> { persisted? }
def validate_attachment_size
if documentable.present? &&
attachment_file_size > documentable.class.max_file_size
errors[:attachment] = I18n.t("documents.errors.messages.in_between",
min: "0 Bytes",
max: "#{max_file_size(documentable)} MB")
end
end
after_save :remove_cached_document, if: -> { valid? && persisted? && cached_attachment.present? }
def validate_attachment_content_type
if documentable.present? &&
!accepted_content_types(documentable).include?(attachment_content_type)
errors[:attachment] = I18n.t("documents.errors.messages.wrong_content_type",
content_type: attachment_content_type,
accepted_content_types: humanized_accepted_content_types(documentable))
end
end
private
def attachment_presence
if attachment.blank? && cached_attachment.blank?
errors[:attachment] = I18n.t("errors.messages.blank")
def validate_attachment_size
if documentable.present? &&
attachment_file_size > documentable.class.max_file_size
errors[:attachment] = I18n.t("documents.errors.messages.in_between",
min: "0 Bytes",
max: "#{max_file_size(documentable)} MB")
end
end
def validate_attachment_content_type
if documentable.present? &&
!accepted_content_types(documentable).include?(attachment_content_type)
errors[:attachment] = I18n.t("documents.errors.messages.wrong_content_type",
content_type: attachment_content_type,
accepted_content_types: humanized_accepted_content_types(documentable))
end
end
def attachment_presence
if attachment.blank? && cached_attachment.blank?
errors[:attachment] = I18n.t("errors.messages.blank")
end
end
def remove_cached_document
File.delete(cached_attachment) if File.exists?(cached_attachment)
end
end
end