首页 > 解决方案 > 使用 ActiveStorage 将 Cloudinary 图像附加到 Rails 模型

问题描述

我有一个用户模型

class User < ApplicationRecord
  has_one_attached :photo
end

我试着:

这是我认为应该工作的

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-railsrubyimagecloudinaryrails-activestorage

解决方案


假设您的 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


推荐阅读