【问题标题】:The proper way of creating association between Ckeditor::Picture and a model in Ruby on Rails?在 Ruby on Rails 中创建 Ckeditor::Picture 和模型之间关联的正确方法?
【发布时间】:2018-08-07 07:28:30
【问题描述】:

我有一个文章模型和 Ckeditor + Paperclip 安装。当我将图片上传到文章正文时,一切正常。但是,我想让这些图片可以通过@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

【问题讨论】:

  • 上传图片时如何创建Ckeditor::Picture的新实例?
  • @Sinstein 这就是我要找的。我不知道在哪里初始化 Ckeditor::Picture 实例并将文章 ID 传递给它。当我尝试以 ckeditor 形式上传图片时,我收到一条警告“文章必须存在”。
  • 试试artcle.create_picture!(&lt;params&gt;)

标签: ruby-on-rails ckeditor model-associations


【解决方案1】:

您不能传递文章 ID,因为在您上传图片时,您的文章并未持久保存(除非您正在编辑已保存的文章)。

所以你可以做的是用一些唯一的token构建一篇文章,然后在上传图片并保存文章后,在所有具有相同token的图片中更新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 字段添加到您的文章模型,并将token 字段添加到Ckeditor::Picture。希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    相关资源
    最近更新 更多