使用 ActiveStorage 将 Cloudinary 图像附加到 Rails 模型
Attach Cloudinary image to Rails model using ActiveStorage
我有一个用户模型
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
我有一个用户模型
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