Action Text with Rails API only application
Action Text is Rails' rich text editing solution, but using it with API-only applications requires some additional configuration. This post covers how to set up Action Text in a Rails API-only application.
The Challenge
Rails API-only applications don't include Action Text by default, and Action Text requires some additional setup since it relies on Active Storage and Trix editor assets.
Setting Up Action Text
1. Add Required Gems
First, ensure you have the necessary gems in your Gemfile:
gem 'actiontext', '~> 7.0'
gem 'activestorage', '~> 7.0'
2. Install Action Text
Run the installation command:
rails action_text:install
This will create the necessary migrations and copy the Trix editor assets.
3. Configure Active Storage
Since Action Text uses Active Storage, you'll need to configure it:
# config/environments/production.rb
config.active_storage.service = :amazon # or :local, :google, etc.
4. Set Up Your Model
Add the rich text association to your model:
class Post < ApplicationRecord
has_rich_text :content
end
API Considerations
Serializing Rich Text Content
When returning Action Text content via your API, you'll want to serialize it properly:
# app/serializers/post_serializer.rb
class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :content
def content
object.content.to_s
end
end
Handling File Uploads
Action Text allows embedded images and attachments. For API-only apps, you'll need to handle direct uploads:
# config/routes.rb
Rails.application.routes.draw do
namespace :api do
resources :posts
post '/direct_uploads', to: 'direct_uploads#create'
end
end
# app/controllers/api/direct_uploads_controller.rb
class Api::DirectUploadsController < ApplicationController
def create
blob = ActiveStorage::Blob.create_before_direct_upload!(
filename: params[:filename],
byte_size: params[:byte_size],
content_type: params[:content_type],
checksum: params[:checksum]
)
render json: {
signed_id: blob.signed_id,
url: blob.service_url_for_direct_upload,
headers: blob.service_headers_for_direct_upload
}
end
end
Frontend Integration
For the frontend, you'll need to include the Trix editor. If you're using a JavaScript framework:
// Install trix via npm
import Trix from 'trix'
import 'trix/dist/trix.css'
// Use in your component
<textarea id="content" name="content" input="trix-input"></textarea>
<trix-editor input="content"></trix-editor>
Best Practices
- CORS Configuration: Ensure CORS is properly configured for file uploads
- Content Sanitization: Consider sanitizing rich text content before saving
- File Size Limits: Set appropriate limits for file uploads
- CDN for Assets: Serve Trix assets from a CDN for better performance
Conclusion
While Action Text requires additional setup for API-only applications, it's definitely possible and provides a powerful rich text editing solution. With proper configuration, you can enjoy all the benefits of Action Text in your API-only Rails application.