Adding Trix Editor in Ruby on Rails 6 applications

This article demonstrates adding ActionText to Rails applications. According to the official ActionText documentation:

Action Text brings rich text content and editing to Rails. It includes the Trix editor that handles everything from formatting to links to quotes to lists to embedded images and galleries. The rich text content generated by the Trix editor is saved in its own RichText model that’s associated with any existing Active Record model in the application. Any embedded images (or other attachments) are automatically stored using Active Storage and associated with the included RichText model.

Here’s how to get started adding rich content functionality to your Rails application:

Installation

1
rails action_text:install

This will create several files and will take care of most of the configuration, but always check that the configuration is correct.

Configuration

Make sure your app/assets/stylesheets/actiontext.scss contains the following line:

1
@import "./actiontext.scss";

And your app/assets/stylesheets/application.scss has the following lines:

1
2
require("trix")
require("@rails/actiontext")

Scaffolding

Now add Blog to the application that requires rich text integration.

1
2
rails generate scaffold Blog title:string
rails db:migrate

In blog.rb, add this:

1
has_rich_text :body

In app/controllers/blogs_controller.rb, permit :body parameter like this:

1
2
3
def blog_params
  params.require(:blog).permit(:title, :body)
end

In app/views/blogs/_form.html.erb, add this:

1
2
<%= form.label :body %>
<%= form.rich_text_area :body %>

In app/views/blogs/show.html.erb, add this:

1
<%= @blog.body %>

Now the body of the blog should be created as shown at the frontend. Happy Blogging!