【发布时间】:2017-05-20 17:27:25
【问题描述】:
我在上传图片时遇到了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 方法,但我无法准确指出它在哪里。请告诉我我错在哪里。
【问题讨论】:
-
检查为什么
!photo?在delete_invalid_image中为真 -
我使用
photo.instance.photo_content_type进行检查并返回nil结果,我只是混淆了在添加cloudinarygem 之前,图像已正确上传... -
我无法重现此问题。它似乎对我来说很成功。具体来说,你能分享一下为什么你选择实现
delete_invalid_image方法而不是validates_presence_of :photo吗?
标签: ruby-on-rails paperclip cloudinary