Modern web application may have a requirement to use rich text editor for a features. When a question arises to use rich text editor, Action Text is my goto option because it is packed and loaded with all lot of features makes rich text content management very easy. Following are some features which are not very highlighted in the Rails documentation:
- Handles and processes inline attachments.
- Direct upload of attachments after processing.
- Generates Preview images for video, PDFs files.
- Control over the rich text content rendered in editor.
- Sanitizes HTML.
The list is long enough to make me comfortable to choose Action Text.
Problem Statement
Action Text does not work well with Rails API only application. I have noticed some similar concerns raised on appropriate channels asking help regarding Action Text with API application.
Why? 🤔
Action Text having a dependency on Action View to render the content and since Rails API only application would not ship with views Action Text would not work.
Solution 🎉
Here is my attempt to solve the problem within Rails by introducing Action Text for API only application. Until the change is accepted or rejected we can follow these steps to use Action Text with API only application.
1. Action Text Model
Normally, running rails action_text:install
should do the trick but since Action Text
installer would try to install NPM dependencies,
add imports statements, etc which are not necessary
in the API only application.
We can ignore running Action Text installer and get
migration by running following command:
./bin/rails action_text:install:migrations
2. Action Text API response
API response should return Action Text Trix HTML.
json.title post.title
json.content post.content.to_trix_html
Web application which consumes
the output of the Action Text rich text content
probably should use Trix editor at frontend.
If you are using some other editors you would
lose some benefits of using Trix editor
with Action Text but you’ll be fine
without Trix as well. Change the API response
to render to_html
instead of to_trix_html
.
json.title post.title
json.content post.content.body.to_html
Another Easy Way(NOT recommend) 🎉
Another easiest way to use Action Text in
API only application is inherit controller from
ApplicationController
instead of ActionController::API
.
This would also need to include Action Text blob views
which are copied with Action Text installer is ran.
I would NOT recommend solving it this way.
Happy Coding!!