How to add a WYSIWYG editor to your rails app.

In my first post, you’ll learn how to add the TinyMCE rich text editor to your rails app.


Recently I found that users of one of our apps (Rocketeer) needed rich text editing capabilities. Instead of using a standard text area, we created a better user experience by allowing users to format their own profiles, highlighting information that they found important.

There are many WYSIWYG editors to choose from, I chose TinyMCE, it’s widely used and is easy to customize.

There’s a handy gem available here: https://github.com/spohlenz/tinymce-rails.

  1. Add the gem to your gemfile.
gem 'tinymce-rails'

2. Run bundle install.

3. Create a config file with your global configuration options in config/tinymce.yml. Take a look at all the configuration options here.

Here’s an example from the gem docs:

default:
plugins:
- image
- link

alternate:
selector: textarea.table-editor
toolbar: styleselect | bold italic | undo redo | table
plugins:
- table

Take note of the syntax.*

4. Include TinyMCE assets. To be able to use TinyMCE sitewide, you have to require it in application.js. Add //= require tinymce above //= require_tree..

5. Initialize TinyMCE by adding a helper to the bottom of your view.

<%= tinymce %> #Add to the bottom of the views that use the editor

6. Add the tinymce class to your text area. We’re using ours in a devise form builder:

<%= f.text_area :description, rows: 5, cols: 25, :class => "tinymce" %>

7. TinyMCE will output raw html, so you need to tell rails to render it using html_safe, here’s an example:

<%= @user.description.html_safe %>

That’s it! Just seven easy steps to a rich text editor. Be sure to check out the documentation for more configuration options.

UPDATE: 2017–07–26

It’s a good idea to change html_safe to sanitize to help prevent XSS attacks (Cross site scripting). sanitize will allow you to filter out any markup tags you don’t want. html_safe is still fine if you’ve got an app for personal use or you’re not worried about this as an attack vector.

See the API for more info: http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.