Rich Text with Trix and Action Text on Rails
Most web applications I work on require a content editing feature that includes formatting, adding images etc. Now Rails comes with that bundled as ActionText. It’s awesome.
Rails version 6 adds ActionText which bundles the Trix Editor.
Action Text brings rich text content and editing to Rails. It includes the Trix editor that handles everything from formatting to links to quotes to lists to embedded images and galleries. The rich text content generated by the Trix editor is saved in its own RichText model that’s associated with any existing Active Record model in the application. Any embedded images (or other attachments) are automatically stored using Active Storage and associated with the included RichText model. (Rails Guides)
It’s a really nice editor, easy to extend and build on, which works out of the box in your Rails app with very little effort. Trix is built by the basecamp team who also invented and contribute to Rails, so it’s a nice cosy and solid relationship.
Getting Started.
To set up ActionText, run the installer:
rails action_text:install
Which should add this to the app/javascript/application.js
require("trix")
require("@rails/actiontext")
To use it, add the macro to your model
class Content < ApplicationRecord
has_rich_text :copy
end
Update your form to use the richtextarea helper
<%= form.rich_text_area :copy %>
Don’t forget to add “copy” to your strong parameters.
At this point, your editor should work, but might look completely unstyled. Cheer it up a bit by including the scss file the installer added. To do this you need to use the require statement, not a sass @include.
//= require actiontext
And tadar! Your have a rich text area.
To add buttons to the toolbar, you need to access the Trix instance, add the attribute to either blockAttributes or textAttributes, as appropriate, and then reconfigure your toolbar html, based off the default from Trix.
var Trix = require("trix")
Trix.config.blockAttributes.heading2 = {
tagName: 'h2'
}
const {lang} = Trix.config;
Trix.config.toolbar = {
getDefaultHTML() { return `\
<div class="trix-button-row">
...
<span class="trix-button-group trix-button-group--block-tools" data-trix-button-group="block-tools">
<button type="button" class="trix-button " data-trix-attribute="heading1" title="h1" tabindex="-1">h1</button>
<button type="button" class="trix-button " data-trix-attribute="heading2" title="h2" tabindex="-1">h2</button>
...
</div>\
`; }
};