Rich Text Fields with Action Text

Many applications need rich text with embeds (i.e. multimedia elements) and Rails provides this functionality out of the box with Action Text.

To use Action Text, you’ll first run the installer:

Terminal window
$ bin/rails action_text:install
$ bin/rails db:migrate

Restart your Rails server to make sure all the new features are loaded.

Now, let’s add a rich text description field to our product.

First, add the following to the Product model:

class Product < ApplicationRecord
has_rich_text :description
validates :name, presence: true
end

The form can now be updated to include a rich text field for editing the description in before the submit button.

<%= form_with model: product do |form| %>
<%# ... %>
<div>
<%= form.label :description, style: "display: block" %>
<%= form.rich_textarea :description %>
</div>
<div>
<%= form.submit %>
</div>
<% end %>

Our controller also needs to permit this new parameter when the form is submitted, so we’ll update the permitted params to include description in

# Only allow a list of trusted parameters through.
def product_params
params.expect(product: [ :name, :description ])
end

We also need to update the show view to display the description in :

<% cache @product do %>
<h1><%= @product.name %></h1>
<%= @product.description %>
<% end %>

The cache key generated by Rails also changes when the view is modified. This makes sure the cache stays in sync with the latest version of the view template.

Create a new product and add a description with bold and italic text. You’ll see that the show page displays the formatted text and editing the product retains this rich text in the text area.

Check out the Action Text Overview to learn more.

Proudly built by Evil Martians based on the Rails Guides.
Files
Preparing Environment
  • Preparing Ruby runtime
  • Prepare development database