This is part one of our multipart series exploring Action Text.
Before introduction to Action Text, adding support for rich-text fields, or WYSIWYG editors was cumbersome. We would choose from several available options like TinyMCE, Trix, and so on. After adding this in views, support to handle file uploads, storage of text and converting back and forth from view vs database, supporting plugins, etc on the backend, were some of the repetitive tasks we would spend time on.
Action Text is a new framework introduced as part of Rails 6 that makes it easy to work with rich text content.
- Creating and editing the rich text
- Storing and rendering the rich text
- Ability to attach and render attachment within rich text editor
- Seamlessly upload the attached files to the chosen cloud provider
Trix is developed by Basecamp.
According to its official website:
Trix is an editor for writing messages, comments, articles, and lists—the simple documents most web apps are made of. It features a sophisticated document model, support for embedded attachments, and outputs terse and consistent HTML.
You can read more about Trix, all the features it offers, and what are its advantages over most other WYSIWYG editors over here.
Setup Action Text
To setup Action Text, we can run the following command from root directory of a Rails 6 app:
Above command will perform the following steps:
package.jsonto add packages for
- Add a migration to create tables needed to support storage of rich text content.
- Add a migration to create tables needed by Active Storage.
app/views/active_storage/blobs/_blob.html.erb: we can modify this file to change how the image uploads and other attachments are rendered.
app/assets/stylesheets/actiontext.scss: we can modify this file to change the styling of Trix editor.
Use a rich text field with an existing model
To add a rich text field to an existing model:
content is not an actual field on the
The rich text data is stored in a internal table called
We can use helper method
rich_text_area to render the field in the form:
This shows an editor like so:
The rich text is stored in database as
We can get the rich text as html string simply by calling method corresponding to the
For example, in case of
Post model describer above
we can use
This is how we can render the content in an html view:
Note, we need to add
to enable rendering of attached images.
In its absence
LoadError (cannot load such file -- mini_magick): error
will be thrown while working with images.
We can modify
to change styling of Trix editor and the content.
To modify how the attachments are rendered we can update
For example you can add a download link to each rendered attachment.
The code would look something like below:
This shows up like:
We looked at basic of how we can get started with providing WYSIWYG support in our Apps using ActionText. In our next post of the series we will look at how to manage and render different types of attachments, media, and more.