Skip to content

Instantly share code, notes, and snippets.

@pedromschmitt
Last active December 14, 2020 18:22
Show Gist options
  • Save pedromschmitt/c38e2d954355a796e6c9ad0fba8461f7 to your computer and use it in GitHub Desktop.
Save pedromschmitt/c38e2d954355a796e6c9ad0fba8461f7 to your computer and use it in GitHub Desktop.
Manual Image Upload to Rails 6, TinyMCE 5 and Carrierwave (WITHOUT using gem 'tinymce-rails-imageupload', because it not support TinyMCE 5 yet)
# db/migrate/20201212155155_create_editor_assets.rb#
# generate with >> rails g model image alt:string hint:string file:string
class CreateEditorAssets < ActiveRecord::Migration[6.0]
 def change
 create_table :editor_assets do |t|
 t.string :alt
 t.string :hint
 t.string :file
 t.timestamps
 end
 end
end

How to upload images with CarrierWave, Rails 6 and TinyMCE 5 without using 'tinymce-rails-imageupload' gem.

  • Add to gemfile and set tinymce-rails like it is describe at it documentation: gem "tinymce-rails", "~> 5.6"

  • create a model to hold assets, and a uploader on carrierwave

  • set a route post

  • create a controller to receive the image and save on carrierwave

  • add image or quickimage button to TinyMCE toolbarr


Thanks to:

# app/uploaders/asset_uploader.rb
class AssetUploader < CarrierWave::Uploader::Base
 include CarrierWave::MiniMagick
 def size_range
 0.megabytes..10.megabytes
 end
 # Override the directory where uploaded files will be stored.
 # This is a sensible default for uploaders that are meant to be mounted:
 def store_dir
 "#uploads/#{model.class.to_s.underscore}/#{model.id}"
 end
 def extension_white_list
 %w[jpg jpeg gif png]
 end
end
# app/models/editor_asset.rb
class EditorAsset < ApplicationRecord
 mount_uploader :file, AssetUploader
end
# config/routes.rb
post 'tinymce_assets', to: 'tinymce_assets#create'
# config/tinymce.yml
toolbar:
- bold italic underline strikethrough
# 'image' button will open a modal with a lot of option to user: width, height, url, and a tab to upload image
# 'quickimage' button will just open the file explorer to user upload directly. Use the better to you.
- image | quickimage
plugins:
- image
- quickbars
quickbars_image_toolbar: alignleft aligncenter alignright
images_upload_url: "/tinymce_assets"
menubar: false
branding: false
quickbars_insert_toolbar: false
# app/controllers/tinymce_assets_controller.rb
class TinymceAssetsController < ApplicationController
 skip_forgery_protection
 def create
 # Take upload from params[:file] and store it somehow...
 # Optionally also accept params[:hint] and consume if needed
 image = EditorAsset.create params.permit(:file, :alt, :hint)
 render json: { location: image.file.url }, content_type: 'text / html'
 end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment