我安装了Article模型,并安装了Ckeditor + Paperclip。当我将图片上传到Article正文时,一切正常。但是,我想通过@ article.pictures访问这些图片,而无需创建单独的图片模型。我已经在Article和Ckeditor :: Picture之间创建了常规关联。但是,当我上传图片时,Ckeditor并不奇怪需要文章ID。我应该在哪里以及如何通过?
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
答案 0 :(得分:0)
您无法传递文章ID,因为在上传图片时,文章不会保留(除非您正在编辑已保存的文章)。
因此,您可以做的是使用一些唯一的令牌构建文章,然后在上传图片并保存该文章之后,在所有具有相同令牌的图片中更新article_id
。
例如:(伪代码,未经测试)
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
很显然,您需要将picture_token
字段添加到Article模型,并将token
字段添加到Ckeditor::Picture
。希望有帮助。