上传图片时我遇到了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
这是图像控制器中的create方法:
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
方法,但我不能确切地指出它在哪里。请告诉我我错在哪里。
答案 0 :(得分:2)
你似乎在使用Paperclip raw和Cloudinary。使用Paperclip和Cloudinary有一个宝石。请尝试使用它。
https://github.com/GoGoCarl/paperclip-cloudinary
宝石说你不能用正斜杠开始:path
。
您应指定要用于存储和访问已保存附件的Paperclip路径模式。该值应该是URL友好的,不应该以正斜杠开头,除了正斜杠之外,只能包含字母数字字符,短划线( - ),句点(。)和下划线(_) 。可以在默认的Paperclip选项中或通过has_attached_file指定路径。
也不要使用photo.path(:large, timestamp: false)
。请改用photo.url
。
https://github.com/thoughtbot/paperclip#view-helpers
此外,您似乎缺少字段。 Paperclip将创建*_file_name
,*_file_size
等字段。我认为您的迁移是错误的。