如何使用 Shrine 播种图像

How do you seed images using Shrine

我无法使用 shrine 播种我的图像,与 carrierwave 不同,下面的代码不起作用。

Profile.create! id: 2,
                user_id: 2, 
                brand: "The Revengers", 
                location: "Azgaurd", 
                phone_number: "send a raven",
                image_data: File.open(Rails.root+"app/assets/images/seed/thor.png")

我也试过

image_data: ImageUploader.new(:store).upload(File.open(Rails.root+"app/assets/images/seed/thor.png"))

但是 returns

JSON::ParserError in Profiles#show
743: unexpected token at '#<ImageUploader::UploadedFile:0x007fd8bc3142e0>'

有神社方式吗?我似乎无法在任何地方找到它。

shrine.rb

require "cloudinary"
require "shrine/storage/cloudinary"


Cloudinary.config(
  cloud_name: ENV['CLOUD_NAME'],
  api_key:ENV['API_KEY'],
  api_secret:ENV['API_SECRET'],
)

Shrine.storages = {
  cache: Shrine::Storage::Cloudinary.new(prefix: "cache"), # for direct 
uploads
  store: Shrine::Storage::Cloudinary.new(prefix: "store"),
}

profile.rb

class Profile < ApplicationRecord
  include ImageUploader[:image]
  belongs_to :user
  has_and_belongs_to_many :genres
  scoped_search on: [:brand]
end

image_uploader.rb

class ImageUploader < Shrine
end

使用Shrine,模型(例如Profile)上的附件属性(例如image_data)是数据库中的文本列(您可以将其定义为jsonjsonb 也一样)。现在应该很清楚,此列不能接受 File 对象(您正在尝试这样做)。

首先您需要使用上传器(例如ImageUploader)将目标文件上传到您配置的 Shrine 存储之一(例如:cache:store):

uploader = ImageUploader.new(:store)
file = File.new(Rails.root.join('app/assets/images/seed/thor.png'))
uploaded_file = uploader.upload(file)

这里上传器的主要方法是#upload,它在输入上接受一个类似IO的对象,returns一个上传文件的表示(ImageUploader::UploadedFile)输出。

至此,您已经有了上传的文件。现在模型 (Profile) 只需要在其附件属性列 (image_data) 中上传文件的 json 表示,如下所示:

Profile.create! id: 2,
                user_id: 2, 
                brand: "The Revengers", 
                location: "Azgaurd", 
                phone_number: "send a raven",
                image_data: uploaded_file.to_json