All Lessons / @mentions for Users with ActionText in Rails 6

@mentions for Users with ActionText in Rails 6

#288 ยท March 11, 2019

Your Teacher | Chris Oliver

Hi, I'm Chris. I'm the creator of GoRails, 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.




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

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.


logo Created with Sketch.

Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

© 2021 GoRails, LLC. All rights reserved.