I got problem with cloudinary
gem when uploading images, here is my image model:
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
here is create method in image controller:
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
When I trying to create(upload) a new image, the log show:
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
you can notice the insert and delete commands were happened simultaneously. I guest the problem come from the create
method, but I cannot point out exactly where is it. Pls show me where I was wrong.
You seem to be using Paperclip raw with Cloudinary. There is a gem to use Paperclip with Cloudinary. Try using that instead.
https://github.com/GoGoCarl/paperclip-cloudinary
That gem says you can't start
:path
with a forward slash.Also don't use
photo.path(:large, timestamp: false)
. Usephoto.url
instead.https://github.com/thoughtbot/paperclip#view-helpers
Also, you seem to be missing fields. Paperclip will create
*_file_name
,*_file_size
, etc. fields. I think your migrations are wrong.https://github.com/thoughtbot/paperclip#usage