1

We're currently doing this to validate uploads for action text and it's working ok. Is there a way to move this validation to the server, i.e. in course.rb instead of in javascript?

models/course.rb

class Course < ApplicationRecord 
  has_rich_text :description
  has_one :description_text, class_name: 'ActionText::RichText', as: :record
end

javascript/packs/application.js

window.addEventListener("trix-file-accept", function(event) {
  const acceptedTypes = ['image/jpeg', 'image/png', 'application/pdf']
  if (!acceptedTypes.includes(event.file.type)) {
    event.preventDefault()
        alert("Attachment types supported are jpeg, png, and pdf")
  }

  const maxFileSize = 1024 * 1024 // 1MB
  if (event.file.size > maxFileSize) {
    event.preventDefault()
        alert("Attachment size must be less than 1 MB")
  }
})
vince
  • 2,374
  • 4
  • 23
  • 39

1 Answers1

0

There's a gem for that - https://github.com/igorkasyanchuk/active_storage_validations

You will be able to write a regular-looking validation in your model:

has_one_attached: file      
validates :file, attached: true, size: { less_than: 100.megabytes , message: 'too big' }
Yshmarov
  • 3,450
  • 1
  • 22
  • 41