Ruby on Rails

Add TinyMCE text editor to a Rails 8 application

Documentation for TinyMCE Rails gem is here

Add tinymce-rails to Gemfile, and run bundle install.

# Gemfile

gem 'tinymce-rails'

Create a config/tinymce.yml file with global configurations.

# config/tinymce.yml

toolbar:
  - styleselect | bold italic | undo redo
  - image | link
plugins:
  - image
  - link

Include TinyMCE assets by adding the script tag to the layout using the tinymce_assets helper.

<!-- app/views/layouts/application.html.erb -->

<%= tinymce_assets data: { turbo_track: "reload" } %>

For each textarea that needs to be set up with TinyMCE, add the tinymce class and ensure it has a unique ID.

<%= f.text_area :content, class: "tinymce", rows: 40, cols: 120 %>

Invoke the tinymce helper at the end of the form page to initialize TinyMCE.

<%= tinymce %>

Show the content by calling the sanitize method on the attribute.

<!-- app/views/pages/show.html.erb -->

<div class="text-content">
  <%= sanitize @page.content %>
</div>

Apply custom styles to the content by adding a class to a content container (in this example a div with class text-content) and by adding TailwindCSS styles under that class.

/* app/assets/stylesheets/application.tailwind.css */

@layer components {
  .text-content h2 { @apply font-bold text-2xl mt-6 mb-4; }

  .text-content p { @apply mb-8; }

  .text-content .p-with-image {
    @apply flex flex-row gap-12 justify-between;
  }
}
← All posts Recent blog posts →