您如何使用神社播种图像

Ric*_*ers 3 ruby-on-rails ruby-on-rails-5 shrine

我无法使用神rine为我的图像播种,与载波不同,以下代码不起作用。

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")
Run Code Online (Sandbox Code Playgroud)

我也尝试过

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

但它返回

JSON::ParserError in Profiles#show
743: unexpected token at '#<ImageUploader::UploadedFile:0x007fd8bc3142e0>'
Run Code Online (Sandbox Code Playgroud)

有圣地吗?我似乎在任何地方都找不到。

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"),
}
Run Code Online (Sandbox Code Playgroud)

profile.rb

class Profile < ApplicationRecord
  include ImageUploader[:image]
  belongs_to :user
  has_and_belongs_to_many :genres
  scoped_search on: [:brand]
end
Run Code Online (Sandbox Code Playgroud)

image_uploader.rb

class ImageUploader < Shrine
end
Run Code Online (Sandbox Code Playgroud)

Was*_*ain 6

使用Shrine的附件属性(如image_data型号(EG) Profile)是数据库中的文本列(你可以将其定义为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)
Run Code Online (Sandbox Code Playgroud)

在这里,上传器的主要方法是#upload,它在输入中采用类似IO的对象,并在输出中返回上载文件(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
Run Code Online (Sandbox Code Playgroud)