Search code examples
ruby-on-railsrails-activestorage

Rails 5.2 + Trix + ActiveStorage


How can I upload images in Trix editor with Rails 5.2 configured with ActiveStorage?

I saw some videos using others uploaders, but could not adapt the idea to ActiveStorage.

Other (maybe) solution is: use ActionText with Rails 5.2. Is it safe to use already?


Solution

  • Active Storage has direct upload js, you need just add:

    //= require activestorage
    

    to your application.js, and then create trix-attachment-add event listener:

    document.addEventListener('trix-attachment-add', function (event) {
      var file = event.attachment.file;
      if (file) {
        var upload = new window.ActiveStorage.DirectUpload(file,'/rails/active_storage/direct_uploads', window);
        upload.create((error, attributes) => {
          if (error) {
            return false;
          } else {        
            return event.attachment.setAttributes({
              url: `/rails/active_storage/blobs/${attributes.signed_id}/${attributes.filename}`,
              href: `/rails/active_storage/blobs/${attributes.signed_id}/${attributes.filename}`,
            });
          }
        });
      }
    });
    

    Hope this helps you!