A Quick Look at Action Text for Rails 6.0

With the highly anticipated release of Rails 6.0 just around the corner, there‘s a lot of excitement in the Rails community around the powerful new features and enhancements coming in this version. One of the headline additions is the brand new Action Text framework, which brings rich text content and editing capabilities to Rails applications. In this post, we‘ll take a closer look at Action Text and walk through a step-by-step example of integrating it into a Rails 6.0 application.

Introduction to Action Text

As a web developer, you‘ve likely worked on applications that require more than just plain text input from users. Blog posts, articles, content management systems, and many other types of apps often need to accept and display rich text content – complete with formatting, images, links, lists, and more. While there are various open source and commercial rich text editors available, integrating them into a Rails app has always required additional setup and wiring.

Action Text aims to simplify all that by deeply integrating rich text editing into the Rails framework. Under the hood, it leverages the excellent open source Trix editor to provide a What-You-See-Is-What-You-Get (WYSIWYG) content authoring experience. Trix was developed by Basecamp to power the rich text editing in their apps, and has an impressive feature set:

  • Intuitive formatting tools for bold, italic, code, quotes, lists, and more
  • Drag-and-drop image uploads (with built-in image resizing and optimization)
  • File attachments
  • Syntax highlighting for code snippets
  • Undo/redo
  • Autosaving
  • Cross-browser support

By baking Trix into Action Text, Rails 6.0 makes it trivial to add sophisticated WYSIWYG editing to your application.

Integrating Action Text in a Rails App

Let‘s see Action Text in…action by building a sample Rails 6.0 blog application. Our app will have a simple Article model with title and body attributes. We‘ll use Action Text to power the rich text editing and storage for the article body.

First, make sure you have a Rails 6.0 app to work with. At the time of this writing, Rails 6.0 is still in beta, so we‘ll specify the –edge flag when generating a new app to get the latest and greatest:

rails new blog --edge 

Once the app is generated, we need to add the Action Text and image_processing gems to our Gemfile. Action Text is included with Rails 6.0 by default, but we need to explicitly add the image_processing gem to enable image uploads:

gem ‘image_processing‘, ‘~> 1.2‘

Run bundle install to install the gem. Next, we need to install Action Text into the app:

rails action_text:install

This generator adds the necessary JavaScript and database migrations. Run the migrations to create the action_text_rich_texts table where the rich text content will be stored:

rails db:migrate

Now we‘re ready to generate our Article model:

rails g model Article title:string
rails db:migrate

Here‘s where the magic of Action Text comes in. To add a rich text body to the Article model, simply add this line:

class Article < ApplicationRecord
  has_rich_text :body
end

The has_rich_text macro sets up an association between the Article model and a new ActionText::RichText model that stores the rich text content. Behind the scenes, it also configures an Active Storage attachment for any embedded images or other files.

Next, let‘s set up the controller and routes for basic CRUD actions on articles:

# config/routes.rb
Rails.application.routes.draw do
  resources :articles
end

# app/controllers/articles_controller.rb 
class ArticlesController < ApplicationController
  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new  
  end

  def create
    @article = Article.new(article_params)

    if @article.save
      redirect_to @article
    else
      render :new
    end
  end

  private
    def article_params
      params.require(:article).permit(:title, :body)
    end
end

Finally, we can create the view template for the new article form. Here‘s where we encounter our first Action Text-specific view helper – the rich_text_area. Using it is as simple as:

<%# app/views/articles/new.html.erb %>


<%= form_with model: @article do |form| %>
  <div>
    <%= form.label :title %><br>
    <%= form.text_field :title %>
  </div>

  <div>
    <%= form.label :body %><br>
    <%= form.rich_text_area :body %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>

The rich_text_area helper renders the Trix editor and sets up the association with the underlying RichText model. By default, it includes all the powerful formatting tools that Trix provides:

Trix Editor Toolbar

Go ahead and create a new article through the form. You‘ll see that the styling and formatting from the Trix editor is carried through when displaying the article:

<%# app/views/articles/show.html.erb %>
<p>
  <strong>Title:</strong>
  <%= @article.title %>
</p>

<p>
  <strong>Body:</strong>
  <%= @article.body %>
</p>

Trix automatically handles images that are pasted or drag-and-dropped into the editor. Files are uploaded and processed by Active Storage, using the image_processing gem we added earlier to create optimized variants for display.

Here‘s what the generated HTML looks like for an article with embedded images and formatting:

<div class="trix-content">

  <div>
    <action-text-attachment sgid="BAh7CEkiCGdpZAY6BkVUSSIpZ2lkOi8vYmxvZy9BY3RpdmVTdG9yYWdlOjpCbG9iLzEGOwBUSSIMcHVycG9zZQY7AFRJIg9hdHRhY2hhYmxlBjsAVEkiD2V4cGlyZXNfYXQGOwBUMA==--19dba7f35f1c6f814ef89341aa0d4c4c28084c78" content-type="image/png" url="https://example.com/rails/active_storage/blobs/redirect/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBCdz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--2a58c38ff3e138fc1c506a331d8795fe40e3f4ca/image.png" filename="image.png" filesize="95716" width="1000" height="667" previewable="true" presentation="gallery"> 
      <figcaption class="attachment__caption">
        My Image
      </figcaption>
    </action-text-attachment>
  </div>
  <blockquote>
    <div>A quote from some profound individual</div>
  </blockquote>
  <ul>
    <li>List 1</li>
    <li>List 2</li>
  </ul>
  <div>
    <br>
  </div>
  <div>Some more <strong>bold</strong> text. And here‘s a link to <a href="https://www.google.com">Google</a>
  </div>
</div>

As you can see, Action Text takes care of associating the image blob with the article, and adds useful metadata to the HTML like width, height, and filesize. The trix-content CSS class is also automatically added, which you can target to style the rich text content to fit with your application design.

Customizing Action Text

Action Text is extremely configurable, allowing you to adapt it to the needs of your application. Some of the key customization options include:

  • Changing the default Trix editor styling
  • Controlling which formatting options are available in the editor toolbar
  • Adding additional content attachment types beyond Active Storage
  • Rendering rich text content on the server-side
  • Creating custom content filters for rendering and sanitizing rich text

See the Action Text Overview guide for more information and examples.

Conclusion

Rails has always been about increasing developer happiness and productivity. Action Text is a perfect example of how the Rails core team continues to introduce high-value functionality through deep integration with the rest of the framework. For any app that needs to handle rich text content, Action Text is a huge step forward in simplicity and power. I‘m excited to use it in my own projects, and can‘t wait to see what the community builds with it. Happy coding!

Similar Posts