Introduction:
In this tutorial, we will walk through the process of seamlessly integrating TinyMCE, a powerful open-source rich text editor, with a Rails 7 application. Additionally, we'll cover the steps to enable image uploading using Active Storage. Follow this step-by-step guide to enhance your Rails app with a feature-rich text editor and efficient image handling.
Step 1: Install TinyMCE
Add the TinyMCE gem to your Gemfile:
gem 'tinymce-rails'
Run bundle install
to install the gem.
Step 2: Configure TinyMCE
Edit the tinymce.yml
configuration file to customize the editor's appearance and functionality. Make sure to include the necessary options for image uploading:
menubar: "insert view format table tools"
toolbar:
- bold italic | link | undo redo | forecolor backcolor | bullist numlist outdent indent | table | uploadimage | code
plugins:
- table
- fullscreen
- image
- code
# Add other plugins as needed
images_upload_url: '/uploader/image'
Step 3: Include TinyMCE Assets
Add TinyMCE assets and initializer to your view:
<%= content_for :page_header do %>
<%= tinymce_assets %>
<% end %>
Include the initializer at the bottom of your page:
<%= tinymce convert_urls: true, uploadimage: true %>
Step 4: Add TinyMCE to Your Page
Place the TinyMCE-enabled text area in your form. Example using form helper:
<%= f.text_area :content, class: "tinymce", rows: 30, style: 'width: 100%' %>
Hidden Tips
If you are using Turbo, add the following meta tags to the top of your page:
<%= content_for :page_header do %>
<%= tinymce_assets %>
<meta name="turbo-cache-control" content="no-cache">
<meta name="turbo-visit-control" content="reload">
<% end %>
Step 5: Image Uploading with Active Storage
If Active Storage is not already set up, uncomment the necessary gem in your Gemfile and run the required migrations:
gem "image_processing", ">= 1.2"
bin/rails active_storage:install
bin/rails db:migrate
Step 6: Create Uploader Controller
Generate an uploader controller and define the image upload action:
rails g controller uploader image
Update the routes to handle the image upload:
post 'uploader/image'
Step 7: Implement Image Upload Logic
In the UploaderController
, handle image uploads:
class UploaderController < ApplicationController
skip_forgery_protection
def image
blob = ActiveStorage::Blob.create_and_upload!(
io: params[:file],
filename: params[:file].original_filename,
content_type: params[:file].content_type
)
render json: { location: url_for(blob) }, content_type: "text/html"
end
end