S3 Specific Upload to Ckeditor Is Hold Up

Tutorial Explaining How To Create Back End WYSIWYG In Ruby on Rails Using The CKEditor Jewel…

Frontline Have Congenital Several CMS Systems With Rails / CKEditor

If y'all're edifice a Ruby-red on Rails CMS, you'll need a way to input text or media. This is generally accomplished with a "WYSIWYG" (what y'all see is what you lot get) editor. These are quite mutual → TinyMCE, Redactor and CKEditor are the most popular.

The trouble with using a WYSIWYG in Rails is tying it into the backend, peculiarly with the image upload functionality. Because Rails handles epitome uploads differently to text, a split flow is required.

Nosotros currently utilize ckeditor (although Redactor is preferred)↴

CKEditor in one of our production apps

CKEditor has been around since 2003, originally named FCKEditor:

We use it because it is fully supported on Rail v+ (via the precious stone ).

Non only this, merely all the plugins & skins available for CKEditor are
fully compatible with the Runway version:

CKEditor has a HUGE library of Plugins & Skins, All Of Which Can Be Used In The Track Gem 😃

If you wanted to await upwardly other WYSIWYG gems, they are here:

  • CKEditor
  • TinyMCE
  • Redactor (requires purchase of Redactor.js)

📂 A Note On Redactor 📂

Redactor is the all-time WYSIWYG in our opinion.

It's VERY light and easy to employ (TinyMCE/CKEditor are fiddly).

Even so, as it costs $199 and is Non widely supported, we currently utilize CKEditor. We do plan to upgrade, and so nosotros'll update this article when nosotros exercise:

Regardless of which library you use (they ALL piece of work in the aforementioned mode),
the fob lies in knowing how they connect to the **BACKEND**

Whilst the CKEditor gem does this out of the box, there are a number of instances where y'all'll demand to change information technology.


This tutorial will explain how information technology works and how you're able to implement WYSIWYG editing in a Rails application ↴

💼 How Information technology Works 💼

ALL WYSIWYG editors work in the same manner.

They replace a <textarea>...</textarea> HTML element with their ain input course. This varies from being an iframe to span / input element.

The difference is how


Again, we won't get into specifics on choosing a WYSIWYG library.

Our recommendation for **this tutorial** is the "CKEditor" gem. Whilst nosotros prefer Redactor, CKEditor support for Rails 5+ is far better…

CKEditor's Rail support is far meliorate

The gem is a port of the original CKEditor javascript library into Runway.

The gem's authors accept as well added several hooks into the Rails ORM system (ActiveRecord / Mongoid etc) which allows information technology to handle uploads:


This gives the gem direct connectivity to the backend, assuasive us to hook into the likes of Paperclip etc, for image uploads.

❗️ Of import ❗ ️→ *Always* Utilise The Repository

As a note, you should pull from the GitHub repository rather than using the gem directly. They don't push new gems very often → there are several primal updates which merely exist in the repo:

A number of essential updates only be in the repo (important).

📢 HTML 📢

To go information technology working, you must offset realize that every WYSIWYG editor
is an ** HTML** parser

What you lot see is the editor's fashion of parsing the HTML to bear witness the "pretty" stylized version to the user. The uncomplicated way of clarifying this is to click on the "source" push button in all the leading WYSIWYG editors:

This will show you all the HTML that's currently being shown by the editor.

This is important because it gives insight into how they work. They're not magic — they take your inputted text, wrap information technology in HTML and then submit the HTML to the server.

You're saving pure HTML to the db:

CKEditor — as with all WYSIWYG editors — parse HTML

Saving HTML straight to the db obviously presents security challenges,
which we'll ignore for at present.

The point is that Runway — like Wordpress, Joomla and other CMS systems — needs to save stylized text to the database. How you do this is dependent on the setup of your models.


This ways that if you lot're looking to build a CMS, you'll need a way to alter the HTML content in your app. Nosotros'll explain how to do this in a 2d.

📖 Images 📖

In terms of uploading images , there are several options.

Because you're updating HTML within the WYSIWYG, it's the equivalent of having a TextArea input form. Images are COMPLETELY dissever.

The way CKEditor handles this — as with other WYSIWYG's — is to create a separate image upload flow (route / controller / model), which allows you to intersperse your HTML with uploaded paradigm objects:

The prototype object is just an <img /> HTML tag

The images demand to exist held in a separate database table, processed by a split model and handled by a split upload facility:

You need a separate DB tabular array for your uploads in Rails

The key with CKEditor is appreciating how all of the upload menstruation works with the other parts of the awarding. One time yous get this, you'll observe implementing WYSIWYG editors quite simple…

📤 Uploads 📤

Although the CKEditor gem comes with inbuilt upload functionality,
it requires several steps to make information technology work.


For experienced developers, these will be elementary, but you demand to know what you lot're doing. You demand…

  • Model
  • DB Table
  • File Upload Plugin (included already)


If you get information technology working properly, hither's what you should expect to see ↴

CKEditor's "File Upload" Functionality In Rails


The model is provided (needs changing), the database table is carve up (needs migrating) and file upload integration is inbuilt into CKEditor already.

The trick with Rails is getting it all to work together

🚦 Installation & Setup 🚦

To get a CMS working in Rails, there are a number of particulars:

  1. Y'all need a place where y'all can input / edit HTML content.
    Nosotros do this in an admin expanse.
  2. You need ckeditor 'southward javascript added to your asset pipeline.
    There are several custom scripts required.
  3. You need to integrate the correct model / backend options.
    We have several tricks for this.

💎Installing The Gem💎

The offset step is installing the gem in your app:

As mentioned, yous need to practice this through the repo — whilst the gem is fine, it is quite far backside the actual repo. We plant several specific pull requests in the repo are required to get it working correctly (specially in Rails v).


Installing the gem will put all the required avails into your app (via the gem):

The CKEditor Gem is a Rails Engine which adds the advisable files to your system

Later installation (packet install), you lot need to include ckeditor/init.js in your nugget pipeline. This is done via the javascript file that will exist nowadays in the area where CKEditor will announced

Since we utilize a separate admin section, we put this into app/assets/admin.java (which is called by the admin layout):

Doing this will put all the required CKEditor files into your JS pipeline. Think of information technology in the same way every bit including jquery — yous're including the files required to get the system working.

It does not include configuration (that'south the next step).

❗️ Of import ❗ ️→ If Using "asset.prefix", Use A Leading Slash

Well-nigh volition NOT take this problem.

All the same, if you are changing the asset path prefix, you'll demand to ensure you include the leading slash, equally information technology will forbid CKEditor from assigning the correct base_path.

The issue is caused by the way it copies non-digest assets in the rake task:

Whoever created the "path" variable should have used File.join or similar

📓 Configuring The Gem 📓

The adjacent pace is to configure the gem.

The way to do this is to include a config.js file in the app/javascripts/ckeditor directory:

This is automatically included into CKEditor, and so there is no demand to integrate manually. This file is used to define the customization of your editor:

app/assets/javascripts/ckeditor/config.js

Whilst it's Non necessary to employ this, it is required if you wish to use image uploads. We'll explain how to configure this properly in a second.

You can read about it here:

❗️ Important ❗ ️→ If Using Skins, Add together Markdown Interpolation

Almost all custom CKEditor skins have .doc files, which pause sprockets (content_type is not supported)

If you want to download skins/plugins, yous will need to fully excerpt them into your app/assets/javascripts/ckeditor/* binder:

Y'all do Not demand any extra plugins/skins to get CKEditor working.

If yous practise add extras, you will as well need to add the plugins & skins folders to your asset manifest. In Rail 5+, this is done through app/assets/config/manifest.js , although it tin be washed other files as required:

/app/assets/config/manifest.js

/app/assets/javascripts/admin.js

Again, this is only required if you add actress plugins/skins to your CKEditor installation. Y'all ONLY need to add One reference to the above (just showing two ways to do it).

💼 Setting Up Rails 💼

Next, we need to get Rails fix.


This is where things go trickier:

  1. We demand a manner to store & manage HTML content
  2. We need a manner to save uploads
  3. We need to make sure information technology all works together


The initial step is to set up the HTML editor.

This can be done in several ways, simply all require a controller, views and model (to shop the content). Y'all must remember, this has Zippo to do with uploads — it'due south totally independent.

The way to get this working is to have a key data-set (HTML) which can be edited as required. This tin can be done with a unmarried controller, views and routes setup. Whilst nosotros do this somewhat differently to near, here is a general setup:

                          #config/routes.rb              
resources :posts #-> url.com/posts/new
#app/models/mail.rb
class Post < ActiveRecord::Base
#id|championship|content|created_at|updated_at
validates :title, :content, presence: true
end
#app/controllers/posts_controller.rb
PostsController < ApplicationController
before_action -> { @mail service = Mail.notice params[:id] }, but: [:edit, :evidence, :update, :destroy]
###########################
###########################
# edit & testify don't need anything - @post divers before activity

###########################
###########################

def new
@mail = Post.new
end

def create
@mail service = Post.new post_params
@post.save
end

def update
@postal service.update post_params
end
def destroy
@post.destroy
cease
###########################
###########################
private def post_params
params.require(:mail service).let(:championship, :content)
finish
end #app/views/posts/alphabetize.html.erb
<% @posts.each practise |post| %>
<%= link_to edit_post_path(@mail service) %>
<% end %>
#app/views/posts/edit.html.erb
<%= render "grade" %>
#app/views/posts/new.html.erb
<%= render "form" %>
#app/views/posts/_form.html.erb
<%= form_for @postal service do |form| %>
<%= form.text_field :title %>
<%= form.cktext_area :content %>
<%= form.submit %>
<% end %>

Equally mentioned, we exercise it differently…


Nosotros have a central model chosen node which has ref & value values:

This allows us to superclass with meta-programming (to create a
"meta" model called Meta::Post ):

Nosotros're Able To Superclass the "Node" model To Create a "Meta::Postal service" model

The Meta::Post model inherits all of the node model's behavior, except it gives us the power to separate the information into Meta::Post objects:

[[ Meta::Mail service.new ]]

Thus, we accept a Dry model which we can utilise to create an input class to edit/create pages:

You can see how to use ckeditor's form helpers here.

From this, we're able to create a set of routes to evidence a simple input class:

./config/routes.rb

… and we're able to populate the form with the appropriate @content from our controller:


Ultimately, what you demand is a Elementary INPUT FORM (<textarea>) which yous're able to demark to CKEditor using the cktext_area form helper. It should exist relatively simple for an experienced dev to implement.

❗️ Important ❗ ️→ Plow Turbolinks OFF

Due to complications with how Turbolinks loads page content, you demand to plough it off for CKEditor. This can be done in one of ii means.

Firstly, the way I accept shown above works perfectly. It prevents Turbolinks from tracking the class element itself. The do good of this is that Turbolinks still runs on the page, assuasive you lot to retain its benefits whilst also enjoying CKEditor.

Secondly, you may wish to follow the advice of CKEditor'southward jewel maintainer and create a separate Turbolinks initialization script:

The result with not using Turbolinks is that if your folio does not refresh (because Turbolinks intercepted the request), CKEditor will not load.

Using i of the above methods to remove CKEditor from Turbolinks' flow volition force it to reload each time y'all invoke the page.

Uploads

Secondly, you will need to gear up up uploads .

This is tricky, so we volition demand to spend some time explaining the process.

Basically, the CKEditor jewel has including a
comprehensive backend to support image & zipper uploads:

The style uploads are handled in Rails comes down to a ready of gems
(Paperclip or Carrierwave), which have HTML file uploads and catechumen
them into ActiveRecord objects.

We met the guys at Thoughtbot (who maintain Paperclip), so nosotros use that
gem, although at that place are few differences between the most pop…

Meeting Thoughtbot In 2014

The gems ALL work by taking an HTML form submit and creating a
tape in the database:

The file is stored on the server/cdn, merely a record is stored in the DB.

This ways that if you're going to utilise one of these gems, they demand to be tied to a specific model & db table. Whilst you lot tin can "attach" a model onto an existing table / model, yous need to add a number of attributes to brand information technology work:

Paperclip requires the to a higher place attributes

In our apps, nosotros use an Asset model, which allows usa to relieve all the
uploads in i central location:

Nosotros Store All Our Uploads In A Central "Assets" Model

For us, this means we're able to only save whatsoever upload to the Asset model.

Others volition add the attachment functionality on height of another model. Both are okay, only yous have to remember that for the multi-model upload, your attachment will but exist available as part of the tape you lot uploaded it to.

This means several things.

Firstly the mode ORM'south work is to take DB data and change information technology into workable objects you can dispense in memory. To upload files on Track, this ways you should only attach "upload" models to information that it shares value with.

Secondly it means that if you wanted to handle uploads, yous'll need to create a separate model/database table to put them into. This is the case with CKEditor

The CKEditor gem comes with a serial of models which allow it to work with the likes of Paperclip or Carrierwave — the difference lies in how it handles the upload menstruum:

To get CKEditor working with uploads, yous need to add together the post-obit code to your app/assets/javascripts/ckeditor/config.js file:

You Demand to blazon the above into your app/avails/javascripts/ckeditor/config.js file (otherwise uploads don't piece of work)

Here is our actual config.coffee file:

Our actual config.js (coffee) file

As you tin can see higher up, you need to set the fileBrowser paths, as well equally the CSRF token (VERY Important).

This should correspond with calculation the CKEditor routes to your app's main directory:

This should be added by running the ckeditor:install generator

Once you have these in identify, you'll need a manner to upload the images.

This is handled by default by the CKEditor precious stone'due south

[[ model ]]

IF you lot wanted to go along your assets in a central model, we use an Asset model with corresponding table. This has a polymorphic association which allows us to associate whatsoever model to it:

[[ Nugget ]]

🔑 Testing The Install🔑

Finally, we need to see if it works.

Recall, the way CKEditor works is to replace <textarea>...</textarea> elements — meaning that y'all still need the required CRUD operations to manage the HTML (controller etc).

On top of this, you also need to ensure that CKEditor is correctly compiling. This can be checked by identifying the various elements in the public folder of the application:

[[ compilation ]]

Lastly, yous then need to manage the

❗️ IMPORTANT ❗ ️→ Add Basepath For Heroku

If you lot're using Heroku and have set up the "assets prefix" in Runway, y'all will need to hardcode CKEditor'south "base of operations path" into the javascript. This is mentioned here:

This is only applicative if you have a different assets prefix to the default.
Here is our code:

app/assets/javascripts/ckeditor/basepath.coffee.erb

🎳Thanks for reading 🎳

If you have any questions, please ask beneath.

beattyeastche.blogspot.com

Source: https://medium.com/ruby-on-rails-web-application-development/how-to-upload-images-with-ckeditor-rubyonrails-cms-uploads-tutorial-a69874724d9b

0 Response to "S3 Specific Upload to Ckeditor Is Hold Up"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel