簡體   English   中英

Rails + Mongoid +載波+ Cloudinary

[英]Rails + Mongoid + Carrierwave + Cloudinary

我正在從Uploadcare遷移到Cloudinary。

但是當我嘗試更新文件字段時,該字段設置為“ old

p = Photo _id: 556d225e69702d45b0000000, created_at: 2015-06-02 03:26:22 UTC, updated_at: 2015-06-02 03:26:22 UTC, file: nil
p.file = p.id
p.save

返回

Photo _id: 556d225e69702d45b0000000, created_at: 2015-06-02 03:26:22 UTC, updated_at: 2015-07-30 19:41:12 UTC, file: "_old_"


p.file = <PhotoUploader:0x007fe96fc86800 @model=#<Photo _id: 556d225e69702d45b0000000, created_at: 2015-06-02 03:26:22 UTC, updated_at: 2015-07-30 19:41:12 UTC, file: "_old_">, @mounted_as=:file, @stored_public_id=nil, @stored_version=nil, @file=nil, @original_filename=nil, @public_id=nil, @storage=#<Cloudinary::CarrierWave::Storage:0x007fe9701f8f18 @uploader=#<PhotoUploader:0x007fe96fc86800 ...>>>

有什么建議嗎?

我發現了問題!

Carrierwave不允許您更改上傳列如果以前沒有圖像上傳。

所以...您必須先上傳示例圖片

p = Photo.find(:id)
p.remote_file_url = "http:sample.com/image.png"
p.save

to Cloudinary options 然后...將您的更改為Cloudinary選項

include Cloudinary::CarrierWave

最后...

p.file = 'cloudinary public id'
p.save

還有GOTCHA!

如果保存模型時未將值分配給上載器字段,然后再分配值,則CarrierWave會將字段臨時設置_old_以強制Mongoid存儲該字段。 持久化模型后,將分配正確的值:

001 > p = Photo.new title: 'Out with the old!'
 => #<Photo _id: 55c76e895d8b01bef0000000, title: "Out with the old!", image: nil, clean: nil>
002 > p.save
 => true
003 > p
 => #<Photo _id: 55c76e895d8b01bef0000000, title: "Out with the old!", image: nil, clean: nil>
004 > p.image = File.open( 'giraffe-small.jpg')
 => #<File:giraffe-small.jpg>
005 > p
 => #<Photo _id: 55c76e895d8b01bef0000000, title: "Out with the old!", image: "_old_", clean: nil>
006 > p.save
 => true
007 > p
 => #<Photo _id: 55c76e895d8b01bef0000000, title: "Out with the old!", image: "image/upload/v1439133413/dyirrctc3ls3ficre7hj.jpg", clean: nil>

請注意,Cloudinary上傳器接受圖像標識符或File對象(請參見下文)。

模型

class Photo
  include Mongoid::Document
  field :title, type: String
  mount_uploader :image, ImageUploader
end

上傳

class ImageUploader < CarrierWave::Uploader::Base
  include Cloudinary::CarrierWave
end

存儲對已經上傳到您的Cloudinary帳戶的圖像的引用

如果您的圖片網址是http://res.cloudinary.com/tocker/image/upload/v1435050504/sample.jpg *

p = Photo.new
p.title = "Existing image"
signature = Cloudinary::Utils.api_sign_request({:public_id=>"sample", :version=>"1435050504"}, Cloudinary.config.api_secret)
p.image = "image/upload/v1435050504/sample#{signature}"
p.save

*圖片網址可以在您的Cloudinary媒體庫中找到

上傳本地圖像文件並存儲參考

p = Photo.new
p.title = "Uploaded local image"
p.image = File.open( path_to_local_image_file)
p.save

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM