ruby-on-rails - 使用 ActiveStorage 将 Cloudinary 图像附加到 Rails 模型
问题描述
我有一个用户模型
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
解决方案
假设您的 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
推荐阅读
- grib - 具有增量更新的 GRIB 文件
- java - 为什么两个看似相同的哈希图在被 gson 序列化时具有不同的行为?
- reactjs - 如何使用相同对象的 FetchAPI 嵌套数组
- docker - 如何使用 docker-compose 将 /var/run/docker.sock usr/bin/docker 挂载到 docker 容器?
- python - X 轴上的年份值
- ios - 如何访问 childByAutoID 下的 Firebase 数据?
- c# - C# 基本类型列表添加通用子实例
- actionscript-3 - 使用 AS3 循环播放 MP4 视频
- python - 使用python检测图像中的文本
- android - 数据绑定使用 Glide 和 kotlin 找不到符号