Thursday, January 28, 2016

Using Froala Editor with Rails

I am using Froala Text Editor (www.froala.com) to have a rich text editor.
In order to use its image upload (including support of pasting images), you need to implement a server side component. The Froala site documentation has an example for php, but I thought I would write a little post on how to achieve this with Rails.

So my main model is called Article, and I wanted to edit the content of the articles using Froala. To support uploading images, I created another model called ArticleAttachment and implemented it with a mounted uploader using CarrierWave:

class ArticleAttachment < ActiveRecord::Base  belongs_to :article
  mount_uploader :attachment, ArticleImageUploader
end


In the Article model, I added this has_many line:

has_many :article_attachments, dependent: :destroy

In the article controller, I implemented two methods: one for adding an image and one for deleting an image:

  def attach
    attachment = @article.article_attachments.create(attachment: params[:attachment])
    if attachment.save
      render :json => {link: attachment.attachment.url}
    else
      render :json => {error: 'failed to save attachment'}, status: 500
    end
  end

  def detach
    src = params[:src]
    uri = URI.parse(src)
    fname = File.basename(uri.path)
    attachment = @article.article_attachments.find_by(attachment: fname)
    if attachment.present? && attachment.destroy
      render :json => {success: 'deleted'}
    else
      render :json => {error: attachment.attachment.url}, status: 500
    end
  end

for that to work, you need to assign a unique file name in the uploader as explained here:
https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Create-random-and-unique-filenames-for-all-versioned-files




And a message from our advertisers:


Toptal provides remote engineers and designers of high quality. I recommend them. Follow this link (full disclosure: this is my affiliate link):
https://www.toptal.com/#engage-honest-computer-engineers-today