New Discussion

Notifications

You’re not receiving notifications from this thread.

Using the Trix Editor plus File Upload Attachments Discussion

52
General

Great vid, can this be done with the carrierwave gem?

Yep, just swap out the Shrine code on the Photos model and you're set.

How hard is it to add trix to a selected input-field in administrate. What should be the best approach?

Really really easy. You need to add the JS and CSS to administrate's versions. Then you can create a custom field. I made one called FormattedText and just added the editor to the form.html.erb view for the field.

<div class="field-unitlabel">
<%= f.label field.attribute %>
</div>
<div class="field-unit
_field">
<%= f.hidden_field field.attribute, id: field.attribute %>
<trix-editor input="&lt;%= field.attribute %&gt;"></trix-editor>
</div>

Tim Passmore Tim Passmore

From what I've read trix doesn't allow any html tags in input. This is good for security but we use some custom css classes. How hard is it to add these to trix locally?

Alex Musayev Alex Musayev

Hey Chris! That was a great episode. Special thanks for the part where you explain the details about image uploading. I've been implementing images processing for few Rails apps, nevertheless some aspects in this area felt like a black magic to me. For example, progress tracking for XHR requests was new.

Alex Musayev Alex Musayev

Also now I know that axios has onUploadProgress callback. Neat. When you know what features to expect, it is much easier to find them.

How add post_id with Photo ?

did you find any solution?

How add association has_many :photos with post.rb after save ?

Hi! How to use jquery_ujs instead of rails-ujs to use trix gem?

xhr.setRequestHeader("X-CSRF-Token", Rails.csrfToken()); Rails. not work

You use

$.rails.csrfToken()

Hmm. So in this example the Post object has no association with Photo. Since Trix isn't handling any sort of deletion, we only add photos and never remove them. We also can't remove a Photo (or the attached image) when a Post is deleted since there's no relationship between them. And because Trix is handling the HTML for the image, I don't have an opportunity to add markup to the image to use, say, Imgix.js to handle responsive adaptations.

If I add a post-processor on the HTML (e.g., parse w/ Nokogiri and manipulate the images as needed), Trix is going to be disagreeable on edit. I could handle that on show and use fragment caching, I suppose. If I use JS to modify what I'm handing Trix, my final output is tied to the JS on a totally different view in an unrelated area of my website, and it's difficult to update down the road. Neither of these options fixes the lack of relationships, either, unfortunately.

How are others handling this in, say, a CMS for a media organization?

How did you end up handling it @coreyward:disqus ? I used a form of post-processing in the past with Refile, curious to know if you came up with a better solution?

Chris! Next video: Trix + ActiveStorage. :)

Stephane Le Boisselier Stephane Le Boisselier

Hi,

Thanks for this great job, i decide to replace Refile with Shrine, but got a problem. In my js xhr.setRequestHeader("X-CSRF-Token", Rails.csrfToken()); generate an error in JS Console, Rails is not define. I tried to update my rails version (previously on 5.0.5) to 5.1.4 but problem is still there :( Any idea ? Thanks

Stephane Le Boisselier Stephane Le Boisselier

I solve this doing :

var token = $('meta[name="csrf-token"]').attr('content');
xhr.setRequestHeader("X-CSRF-Token", token);

But I don't understand why xhr.setRequestHeader("X-CSRF-Token", Rails.csrfToken()); is not working.

Other question, How do you do to have the full url image in src ? I only have /uploads/blablabla, and I have to send html with my api to a mobile app so, I need the full url.

Thanks for your help

Gabriel Sigouin Gabriel Sigouin

In development on cloud9 my trix editor work well, but in production on Heroku, i cannot write on the text area. Anyone know how i can fix this issue?

I tried to combine this with the direct S3 uploads and keep the URL's private. It's working well for me so far so here are the changes i made in a gist https://gist.github.com/The...
I am a relative novice in Javascript so if anyone has corrections or improvements I would love to know :)

Thanks for sharing Neil!

I really need help with trix, i dont know what iam doing wrong, but Trix isnt working for me in Rails 5.2.
I did everything like in the setup explained but i had my postmodel before.
so as you can see i have a field called t.text "content" - and everywhere trix is referring to a body. Is that the issue? How can i change the migration so that my content is a body? And! If that even needed? I mean if i switch in my code body for content it is supposed to work aswell right?

My Schema looks like this:
create_table "posts", force: :cascade do |t|
t.string "title"
t.text "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "slug"
t.index ["slug"], name: "index_posts_on_slug", unique: true
end

I wish I could help but I don't know the answer. Why don't you try the GoRails Slack?

I had the same question regarding how to get around using t.text "body" as I would also like to add trix to a preexisting project where I have used "content". Did you find an answer?

I suppose I could just do a rename_column to change content to body in the db ...

great! super useful!

How can this been done for live direct upload? I watched the aws direct videos but my JS skills arent strong enough to get it to work https://github.com/cgibsonmm/Sprout-Free

I'm getting a Javascript error saying the variable Trix is not defined when trying to disable captions and file size display. Any ideas?

Make sure you import Trix in your JS.

Thanks for the quick reply.

I'm pretty certain it is importing, I see the link in the head.

Still haven't been able to get this working and wanted to provide a bit more detail.

In my application.js I do have //= require trix and I can see the file in the head of the page; however, it does not look like the same file that appears on trix-editor.org. It seems mostly the same, but if I do a search in the files for the keyword "config" I get 47 matches in the file on my app and 56 in the file on trix-editor.org.

Could this be a versioning issue?

ADDING A CUSTOM BUTTON TO THE TRIX EDITOR FOR PHOTO UPLOADS?

We have the photo uploads working now (THANK YOU CHRIS FOR A GREAT TUTORIAL!), but unfortunately, there is no 'drag and drop' option on mobile, so it means only those users on desktop can add a photo to their posts. I've been searching on google for a tutorial on how to add a custom button to the Trix editor.

Any thoughts? Has anyone done it before?

Has anyone tried saving a reference to to the Photo record within the post.body, rather than the URL itself?

I think that's how Action Text does it when using Active Storage. They include the Global ID ( gid://app/Photo/123 ) instead of the URL of the image itself. Then, when the post.body gets rendered you're free to display it anyway you want.

ActionText uses attachable_sgid from the Attachable concern. That's covered in the @mentions in ActionText video on how that works.

How do I integrate Trix with ActiveStorage and AWS S3? Thank you!

In case somebody needs it. Here are the steps to make it work.

  1. Set up your S3 bucket. Use this CORS on the bucket: https://github.com/basecamp/trix/issues/128#issuecomment-523545259
  2. Allow List Objects, and Write Objects for the public. Not exactly safe, but it allows you to upload without presigning.
  3. Optionally add Cloudfront and allow POST.
  4. Take note of your Cloudfront URL.
  5. Add this to your https://trix-editor.org/js/attachments.js application.js
  6. Change the HOST to your cloudfront URL.

Chris' code did not work for me.

This is what worked for me, given I am using webpacker:

/// app/javascript/packs/application.js
// add this line:
require("../trix_attachments.js")

// now we have to add the above javascript file in
// I have included it outside the packs folder
// if you want to change the location, be sure to also change the path:

// Listen for the Trix attachment event to trigger upload
document.addEventListener("trix-attachment-add", function(event) {
  var attachment = event.attachment;
  if (attachment.file) {
    return uploadAttachment(attachment);
  }
});

function uploadAttachment(attachment) {

  // Create our form data to submit
  var file = attachment.file;
  var form = new FormData;
  form.append("Content-Type", file.type);
  form.append("document[file]", file); // change to suit your circumstances!!

  // Create our XHR request
  var xhr = new XMLHttpRequest;
  xhr.open("POST", "/documents.json", true);

    // I am posting to the doucments route - your situation may be different!

  var csrfToken = $('meta[name="csrf-token"]').attr('content');
  xhr.setRequestHeader("X-CSRF-Token", csrfToken);  

  // Report file uploads back to Trix
  xhr.upload.onprogress = function(event) {
    var progress = event.loaded / event.total * 100;
    attachment.setUploadProgress(progress);
  }

  // Tell Trix what url and href to use on successful upload
  xhr.onload = function() {
    if (xhr.status === 201) {
      var data = JSON.parse(xhr.responseText);
      return attachment.setAttributes({
        url: data.image_url,
        href: data.url
      })
    }
  }

  return xhr.send(form);
}

Enjoy! And I hope that helps.

Another possibility to add in Trix into your project is following the 2 steps in the installation guide.
https://edgeguides.rubyonrails.org/action_text_overview.html

Chris, How hard is that to add a html table and change the text color in the trix editor.

Hi everybody,
I'm facing an issue I'll quickly describe.
I'm using rails 6 and was using Webpack to get ActiveStorage ActionText and Trix working all togother. Everything was OK : text edit and multiple files uploading via trix. WOUHOU !!!!

But.

Now, I going back to Sprockets. My custommer is asking me for.
So, here is what I did.

  • Checking ActiveStorage working with a simple f.file_field to upload images = OK!
  • Installed Trix with one of the existing gems. = OK for text editing :)
  • Trying to upload files with trix : KO !!

So,

  • Why it was working with Webpack ? Is it because of the upload js file you're using in this video ? This file was present in the node_module trix but not in the gem ?
  • I've tried the file you're using but it doesn't work. I've got console error : "Uncaught TypeError: Cannot read property 'preview' of undefined" on the line "Trix.config.attachments.preview.caption = ..."
  • What gem would you use for my config : Rails6 + Sprockets ?

Can someone help me please ?

Thanks a lot.

Philippe

Thanks for the episode. Trix is easy and works great but is there a way to style the images. I managed to get them to align left or right but cannot get them to float left or right with text around them.

Hi there! Any idea why uploading works in development locally, but not on ngrok or in production?
I get this:
application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:18352 Uncaught Error: Direct upload failed: Error creating Blob for "PHOTO-2023-08-07-19-34-45.jpg". Status: 0
at AttachmentUpload.directUploadDidComplete (application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:18352:15)
at BlobRecord.callback (application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:18125:17)
at BlobRecord.requestDidError (application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:18067:16)
at XMLHttpRequest. (application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:18035:62)
directUploadDidComplete @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:18352
(anonymous) @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:18125
requestDidError @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:18067
(anonymous) @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:18035
error (async)
BlobRecord @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:18035
(anonymous) @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:18121
fileReaderDidLoad @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:17952
(anonymous) @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:17943
load (async)
create @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:17943
create @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:17931
create @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:18116
start @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:18342
(anonymous) @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:18373
g @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:12279
notify @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:17446
notifyEditorElement @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:17300
compositionDidAddAttachment @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:17088
(anonymous) @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:15404
(anonymous) @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:15402
refreshAttachments @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:15406
setDocument @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:15007
insertText @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:15020
insertAttachments @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:15090
insertFiles @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:15077
insertFiles @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:15590
(anonymous) @ application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:12396
application-f91eb14d1a71eb1bded7bacba5a2c9f6e50d1ef47606669468a65584ed3f021d.js:18050 POST http://localhost/rails/active_storage/direct_uploads net::ERR_CONNECTION_REFUSED

Thanks a lot!

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 88,834+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.