Track your progress

Sign in to track your progress and access subscription-only lessons.

Log In

Your Teacher

Hi, I'm Chris. I'm the creator of GoRails, Hatchbox.io and Jumpstart. I spend my time creating tutorials and tools to help Ruby on Rails developers build apps better and faster.

About This Episode

Mentioning Users with an @mention is a super common feature. Trix and ActionText are now part of Rails 6 which means we can very easily add support for tagging users with @mentions and other custom attachments in your applications.

Notes

Resources

Notes

ActionText strips out the HTML from attachments on save in order to always render the current data of each attachment. If it just saved the HTML, the content could go stale if the related records changed. ActionText uses a GlobalID to reference the model for the attachment, allowing you to look up the record for each attachment and then render the partial for the attachment's HTML representation.

ActionText requires custom attachments to have a signed Global ID sgid attribute on them. We can get the sgid by including the ActionText::Attachable module on our ActiveModel objects.

class User < ApplicationRecord
  include ActionText::Attachable
end

You will have to send the sgid to the client using an AJAX request or ActionCable.

Then in our Javascript, we can attach the User with a Trix.Attachment.

let attachment = new Trix.Attachment({
  sgid: mention.sgid,
  content: mention.content
})

ActionText will automatically render the model's partial using to_partial_path when it renders the attachment. It will do the same when rendering the attachment again in the Trix form field. You'll want to render this template as well for the content attribute of the Trix.Attachment so the attachment looks the same in all 3 cases.

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

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

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

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2024 GoRails, LLC. All rights reserved.