Rails 5.2 + Trix + ActiveStorage

Fer*_*ndo 5 ruby-on-rails rails-activestorage

如何在配置了 ActiveStorage 的 Rails 5.2 的 Trix 编辑器中上传图像?

我看到了一些使用其他上传器的视频,但无法将这个想法应用于 ActiveStorage。

其他(可能)解决方案是:在 Rails 5.2 中使用 ActionText。已经可以安全使用了吗?

小智 11

Active Storage 有直接上传js,你只需要添加:

//= require activestorage
Run Code Online (Sandbox Code Playgroud)

到您的 application.js,然后创建 trix-attachment-add 事件侦听器:

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}`,
        });
      }
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

希望这对你有帮助!

  • 谢谢!代码看起来不错,但我已经准备迁移到 RoR 6,这将“默认”启用此功能 (2认同)