13

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.

Ramyani
  • 1,019
  • 1
  • 9
  • 12

2 Answers2

15

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

Yshmarov
  • 3,450
  • 1
  • 22
  • 41
  • Hi Yshmarov, This will hide the attachment button from rich text editor panel in the view. But how can we restrict this from backend as well, Also how can we remove the unnecessary tables (eg: active_storage_attachments, active_storage_blobs) from db as they should not be required. But still if we remove then it is getting error. during saving the object. That means internally it is still getting used even if we are not adding any attachment. Is there any way to get rid of that? – Ramyani May 20 '20 at 12:37
  • Hi @Ramyani, Did you find a way to do this? – Chris Hawkins Aug 22 '20 at 19:32
  • @Ramyani - https://github.com/igorkasyanchuk/active_storage_validations this gem to validate attachments can also help – Yshmarov Aug 24 '20 at 08:28
7

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.

Carlo Beltrame
  • 433
  • 5
  • 10