I have an Article model and Ckeditor + Paperclip installed. When I upload pictures into Article body, everything works fine. However, I want to make these pictures accessible via @article.pictures without creating a separate Picture model. I've already created a regular association between Article and Ckeditor::Picture. But when I'm uploading a picture, Ckeditor not surprisingly requires an Article id. Where and how am I supposed to pass it?
class CreateCkeditorAssets < ActiveRecord::Migration[5.2]
t.references :article, foreign_key: true
end
class Article < ApplicationRecord
has_many :pictures, class_name: 'Ckeditor::Picture'
end
class Ckeditor::Picture < Ckeditor::Asset
belongs_to :article
end
You can't pass an article ID, because at the time when you upload pictures your article isn't persisted (unless you're editing an already saved article).
So what you can do is to build an article with some unique token, then after uploading pictures and saving the article, update article_id
in all pictures that have the same token.
Like this: (pseudocode, not tested)
class Article < ApplicationRecord
has_many :pictures, class_name: 'Ckeditor::Picture'
after_save :assign_pictures
private
def assign_pictures
Ckeditor::Picture.where(token: picture_token).update_all(article_id: id)
end
end
-
class Ckeditor::Picture < Ckeditor::Asset
belongs_to :article, optional: true
end
-
class Ckeditor::PicturesController
def create
@picture = Ckeditor::Picture.new
@picture.token = params[:picture_token] # pass this param via javascript, see: https://github.com/galetahub/ckeditor/blob/dc2cef2c2c3358124ebd86ca2ef2335cc898b41f/app/assets/javascripts/ckeditor/filebrowser/javascripts/fileuploader.js#L251-L256
super
end
end
-
class ArticlesController < ApplicationController
def new
@article = Article.new(picture_token: SecureRandom.hex)
end
end
Obviosly you need to add picture_token
field to your Article model and token
field to Ckeditor::Picture
. Hope that helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.