Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 514
Fernando Avatar asked Dec 18 '18 15:12

Fernando


1 Answers

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!

like image 109
Qurane Avatar answered Oct 18 '22 21:10

Qurane