Как прикрепить изображение к редактору Trix? - PullRequest
0 голосов
/ 18 апреля 2019

Я использую Ruby on Rails, gem 'trix-rails' и вложенный гем для загрузки изображений

Я пытаюсь сделать возможным прикрепление изображения в редакторе Trix.

Изображение прикреплено, но я просто не могу понять, как сделать его видимым

Вот мой код:

picture.rb

class Picture
  include Mongoid::Document
  include Mongoid::Attributes::Dynamic
  has_attachment :image, accept: [:jpg, :png, :gif]
end

pictures_controller.rb

class PicturesController < ApplicationController
  def create
    @picture = Picture.new(picture_params)
    @picture.save
    respond_to do |format|
      format.json { render json: { url: @picture.image, picture_id: @picture.id } }
    end
  end

  def destroy
    @picture = Picture.find(params[:id])
    @picture.destroy
    respond_to do |format|
      format.json { render json: { status: :ok } }
    end
  end

  private
    def picture_params
      params.require(:picture).permit(:image)
    end
end

picture.js.coffee

# TRIX
document.addEventListener 'trix-attachment-add', (event) ->
  attachment = event.attachment
  if attachment.file
    return sendFile(attachment)
  return

document.addEventListener 'trix-attachment-remove', (event) ->
  attachment = event.attachment
  deleteFile attachment

sendFile = (attachment) ->
  file = attachment.file
  form = new FormData
  form.append 'Content-Type', file.type
  form.append 'picture[image]', file
  xhr = new XMLHttpRequest
  xhr.open 'POST', '/pictures/', true
  xhr.setRequestHeader 'X-CSRF-Token', $('meta[name="csrf-token"]').attr('content')

  xhr.upload.onprogress = (event) ->
    progress = undefined
    progress = event.loaded / event.total * 100
    attachment.setUploadProgress progress

  xhr.onload = ->
    response = JSON.parse(@responseText)
    attachment.setAttributes
      url: response.url
      picture_id: response.picture_id
      href: response.url

  xhr.send form


deleteFile = (n) ->
  # $.ajax
  #   type: 'DELETE'
  #   url: '/pictures/' + n.attachment.attributes.values.picture_id
  #   cache: false
  #   contentType: false
  #   processData: false
  xhr = new XMLHttpRequest
  xhr.open 'DELETE', '/pictures/' + n.attachment.attributes.values.picture_id, false

return

Я думаю, что проблема здесь:

  xhr.onload = ->
    response = JSON.parse(@responseText)
    attachment.setAttributes
      url: response.url
      picture_id: response.picture_id
      href: response.url
...