2017-01-06 59 views
1

我得到了上傳圖片時,問題cloudinary寶石,這裏是我的形象型號:不能上傳圖片到使用Cloudinary(回形針)寶石雲 - Rails的

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 

你CA注意插入和刪除命令同時發生。我客人來自create方法的問題,但我不能指出它究竟在哪裏。請告訴我我錯在哪裏。

+0

檢查爲什麼'!照片'是在'真delete_invalid_image' – emaillenin

+0

我用'photo.instance.photo_content_type'檢查,並返回'nil'結果,我被搞亂,在我加上'cloudinary '寶石,圖像上傳正確... – DinhNgocHien

+0

我無法重現此問題。它似乎對我成功運作。具體來說,你可以分享爲什麼你選擇實施'delete_invalid_image'方法而不是'validates_presence_of:photo'嗎? –

回答

2

你似乎在用Cloudinary使用Paperclip raw。與Cloudinary一起使用Paperclip有一個寶石。嘗試使用它。

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

創業板說,你不能以正斜槓開始:path

您應該指定希望用於存儲和訪問保存的附件的回形針路徑模式。該值應該是URL友好的,不應以正斜槓開頭,除了正斜槓外,只能包含字母數字字符,破折號( - ),句點(。)和下劃線(_)。路徑可以在默認的Paperclip選項中指定,也可以通過has_attached_file指定。

也請勿使用photo.path(:large, timestamp: false)。改爲使用photo.url

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

而且,你似乎缺少領域。回形針將創建*_file_name,*_file_size等字段。我認爲你的遷移是錯誤的。

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