Home > front end >  How to specify the allowed attachment file types for Action Text in Rails 7?
How to specify the allowed attachment file types for Action Text in Rails 7?

Time:12-27

I want to specify my ActionText to only allow image file types. I tried this in my model rb file:

has_rich_text :content, attachments: { content_type: ['image/png', 'image/jpg', 'image/jpeg', 'image/gif'] }

but I get this error:

unknown keyword: :attachments

CodePudding user response:

has_rich_text does not have attachments option.

You have to use has_one_attached for image attachments. These attached images can be easily referred in action text using sgid. Reference

has_many_attached :photos

For validation on content type:

validates :photos, attached: true, content_type: ['image/png', 'image/jpeg']

For referencing the sgid (Signed GlobalID) :

photo.to_signed_global_id.to_s # here photo is one photo object

CodePudding user response:

I'd imagine you have to override/decorate RichText model to add some validations, but I'm not sure how that would work.

On the other hand, rejecting files on the front end is easy:

// app/javascript/application.js

import "trix"
import "@rails/actiontext"

const allowedImageTypes = ["image/png", "image/jpg", "image/jpeg", "image/gif"]

document.addEventListener("trix-file-accept", e => {
  if (allowedImageTypes.includes(e.file.type)) {
    console.log("attach");
  } else {
    e.preventDefault();
    console.log("reject");
    // TODO: show useful notification
  }
})

https://github.com/basecamp/trix#storing-attached-files

That's all you need, but if you want to have server side validation, you'll have to upload file to your own controller and do all the extra work of inserting result into trix editor all of which is normally done by @rails/actiontext:

https://github.com/rails/rails/blob/v7.0.4/actiontext/app/javascript/actiontext/attachment_upload.js


Update

Never mind the extra work, figured it out. Above javascript for the front end and this for backend validations:

ALLOWED_IMAGE_TYPES = %w[image/png image/jpg image/jpeg image/gif]

# NOTE: this creates a `has_one :rich_text_#{name}` association where
#       attachments can be accessed
has_rich_text :content

after_validation do
  rich_text_content.body.attachables.each do |attachment|
    unless ALLOWED_IMAGE_TYPES.include? attachment.content_type
      errors.add(:content, "includes unsupported image type")
    end
  end
end
  • Related