无法使用 Cloudinary(paperclip) 将图像上传到云端 gem - Rails

Cannot upload images to the cloud using Cloudinary(paperclip) gem - Rails

上传图片时 cloudinary gem 出现问题,这是我的图片模型:

class Image < ApplicationRecord

  default_scope { where.not(photo_file_name: [nil, ""]).where.not(photo_content_type: [nil, ""]) }
  belongs_to :article, optional: true

  after_save :delete_invalid_image

  has_attached_file :photo, :storage => :cloudinary, path: "/uploaded/:class/:attachment/:id/:style_:filename", styles: { thumb: "300x200#", large: "1024x768>"}
  validates_attachment_content_type :photo, content_type: /\Aimage\/.*\Z/
  #attr_accessor :photo

  def original_photo_url
      photo.path(:large, timestamp: false)
  end

  paginates_per 30

  private

    def delete_invalid_image
      if !photo?
          self.destroy
      end
    end
end

这是图像控制器中的创建方法:

def create
      if !params[:hint].nil?
        @image = Image.new(photo: params[:file])
        if @image.save
            render json: {
              image: {
            url: @image.original_photo_url,
                  id: @image.id
              }
            }, content_type: "text/html"
        else
            render json: {
              error: "Something is wrong"
            }, content_type: "text/html"
        end
      else
        image = Image.create!(image_params)
        if params[:ajax_upload].present?
            image = {
              id: image.id,
              title: image.title,
              caption: image.caption,
              description: image.description,
              width: image.width,
              height: image.height,
          url: image.photo.path(:thumb)
            }
            respond_to do |format|
              format.json { render json: {image: image}}
            end
        else
            redirect_to admin_images_path
        end
      end
  end

当我尝试创建(上传)新图像时,日志显示:

SQL (7.6ms)  INSERT INTO `images` (`caption`, `description`, `title`, `created_at`, `updated_at`) VALUES ('', '', '14696760_1230106580395129_29071409_n', '2017-01-06 00:43:51', '2017-01-06 00:43:51')
SQL (7.2ms)  DELETE FROM `images` WHERE `images`.`id` = 22

您可以注意到插入和删除命令是同时发生的。我猜问题来自 create 方法,但我无法指出它的确切位置。请告诉我哪里错了。

您似乎在 Cloudinary 中使用 Paperclip raw。有一个 gem 可以将 Paperclip 与 Cloudinary 一起使用。尝试改用它。

https://github.com/GoGoCarl/paperclip-cloudinary

那个 gem 说你不能用正斜杠开始 :path

You should specify the Paperclip path pattern that you would like to use to store and access your saved attachments. The value should be URL-friendly, should NOT begin with a forward slash, and, aside from forward slashes, can only contain alphanumeric characters, dashes (-), periods (.) and underscores (_). The path can be specified in your default Paperclip options or via has_attached_file.

也不要使用 photo.path(:large, timestamp: false)。请改用 photo.url

https://github.com/thoughtbot/paperclip#view-helpers

此外,您似乎缺少字段。 Paperclip 将创建 *_file_name*_file_size 等字段。我认为你的迁移是错误的。

https://github.com/thoughtbot/paperclip#usage