0

我正在 Rails 中重建一个博客,并且我正在使用 Trix 作为我的文本编辑器。我已经建立并准备好了有关 Trix 的一切。我可以将图像拖放到 Trix 文本编辑器中,当我单击创建文章时,我没有收到任何错误。但是当我去查看文章时,没有图像。这似乎是一个非常容易解决的问题。

显示.html.erb

<h1>Showing Blog Posts</h1>

<p>
  <strong>Title:</strong>
  <%= @article.title %>
</p>

<p>
  <strong>Text:</strong>
  <%= @article.text.html_safe %>
</p>

<%= link_to 'Back', articles_path %>

article_controller.rb

class ArticlesController < ApplicationController
    def index
       @articles = Article.all 
    end

    def show
       @article = Article.find(params[:id]) 
    end

    def new
        @article = Article.new
    end

    def create
        @article = Article.new(article_params)

        if @article.save
          redirect_to @article
        else
          render 'new'
        end
    end

    def update 
       @article = Article.find(params[:id])

       if @article.update(article_params)
           redirect_to @article
       else
           render 'edit'
       end
    end

    private
        def article_params
            params.require(:article).permit(:title, :text)
        end
end

articles.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 'image[image]', file
    xhr = new XMLHttpRequest
    xhr.open 'POST', '/images', true

    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
        image_id: response.image_id
        href: response.url

    xhr.send form

  deleteFile = (n) ->
    $.ajax
      type: 'DELETE'
      url: '/images/' + n.attachment.attributes.values.image_id
      cache: false
      contentType: false
      processData: false

  return
4

0 回答 0