【问题标题】:Attach Cloudinary image to Rails model using ActiveStorage使用 ActiveStorage 将 Cloudinary 图像附加到 Rails 模型
【发布时间】:2020-04-24 13:05:53
【问题描述】:

我有一个用户模型

class User < ApplicationRecord
  has_one_attached :photo
end

我正在尝试:

  • 通过 URL 将图像上传到 Cloudinary(可行)
  • 将其附加到使用 ActiveStorage 的用户实例(这不是)

这是我认为应该起作用的方法

user_img_response = Cloudinary::Uploader.upload("https://www.formula1.com/content/dam/fom-website/manual/Misc/2019-Races/Monaco2019/Monaco%20chicane%20HAM%20VER%20sized.jpg.transform/9col/image.jpg")

img_id = user_img_response["url"].match(/image\/upload.*/)[0]
signature = "#{img_id}##{user_img_response["signature"]}"

preloaded_file = Cloudinary::PreloadedFile.new(signature)
user = User.new(title: "Chris")
user.photo = preloaded_file

user.save
=> true

但是,照片没有附加到用户实例

user.photo.attached? 
=> false

【问题讨论】:

    标签: ruby-on-rails ruby image cloudinary rails-activestorage


    【解决方案1】:

    假设您的 app/models/photo.rb 与此类似:

    class Photo < ActiveRecord::Base
      attr_accessible :title, :bytes, :image, :image_cache
    
      belongs_to :album
    
      mount_uploader :image, ImageUploader
    
      validates_presence_of :title, :image
    end
    

    如果你尝试会发生什么:

    ...
    user = User.new(title: "Chris")
    user.photo.image = preloaded_file # <---- assign file to image attribute
    user.save
    

    您也可以尝试为您的案例模拟此示例应用程序:https://github.com/cloudinary/cloudinary_gem/tree/master/samples/photo_album

    编辑:你可以试试这样的:

    require 'uri'
    
    file = URI.open(user_img_response["url"]) # use cloudinary url
    photo.image.attach(io: file, filename: 'image.jpg') 
    

    见:https://blog.eq8.eu/til/upload-remote-file-from-url-with-activestorage-rails.html

    【讨论】:

    • 感谢draganstankovic 的回复!这个例子似乎使用了 CarrierWave,我应该提到我正在使用 ActiveStorage(更新的问题)。这是分配给图像属性的好主意。这导致“*** Module::DelegationError Exception: image= delegated to attachment, but attachment is nil”,
    • 感谢@draganstankovic 的后续编辑!如果我使用 cloudinary url,它会复制图像。如果我将原始图像 url 与 File.open 一起使用,则很容易修复。出于好奇,我仍然想知道是否可以使用 Cloudinary:: Uploader 上传到 Cloudinary 并附加到模型。
    • 我想说的是,通过像在编辑中一样直接附加文件并将您的活动存储服务指定为 Cloudinary (cloudinary.com/documentation/rails_activestorage),保存用户基本上会触发正确使用 cloudinary 上传。如果您好奇,可以查看源代码(上传由服务完成):github.com/cloudinary/cloudinary_gem/blob/master/lib/… 看看您是否可以扩展它以满足您的需求...
    猜你喜欢
    • 2019-10-23
    • 2020-03-15
    • 1970-01-01
    • 2021-04-12
    • 2020-09-25
    • 2014-11-25
    • 1970-01-01
    • 2021-12-20
    • 2019-02-18
    相关资源
    最近更新 更多