Is there any way to disable image/attachment part for action text in Rails 6?

Viewed 2587

Do we have a way to disable attachment for action text? something like below has_rich_text :content, attachment: false

So that, We can remove active_storage_blobs, active_storage_attachments tables from db. Only having action_text_rich_texts table should meet the purpose in that case.

2 Answers

Absolutely!

  1. add this to your application.js to block attachments:
    window.addEventListener("trix-file-accept", function(event) {
      event.preventDefault()
      alert("File attachment not supported!")
    })
  1. hide css attachment button - add this in application.scss:
    .trix-button-group--file-tools { display: none !important; }

Even more, here's a commit where this is done in a real application (first 2 files):

https://github.com/yshmarov/pikaburuby/commit/77aaa3e072de943470e4bd2c2b3512727c30232d

I have written a custom validator that can be used for the backend part:

class NoAttachmentsValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    if value.body.attachments.any?
      record.errors[attribute] << I18n.t('errors.messages.attachments_not_allowed')
    end
  end
end

You can save this code into a file called no_attachments_validator.rb, and then use it in your models as follows:

validates :content, no_attachments: true

This works reasonably well in combination with the frontend modifications proposed by Yshmarov.

Related