使用ActiveStorage将Cloudinary映像附加到Rails模型中

问题描述 投票:0回答:1

我有一个用户模型

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个回答
0
投票
假设您的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
© www.soinside.com 2019 - 2024. All rights reserved.