我无法使用 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"))
但它返回
JSON::ParserError in Profiles#show
743: unexpected token at '#<ImageUploader::UploadedFile:0x007fd8bc3142e0>'
有神社之路吗?我似乎在任何地方都找不到它。
神社.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"),
}
个人资料.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
,模型(例如 image_data
)上的附件属性(例如 Profile
)是数据库中的文本列(您也可以将其定义为 json
或 jsonb
)。现在应该很清楚,该列不能接受 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)
这里 uploader 的主要方法是 #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
关于ruby-on-rails - 如何使用 Shrine 播种图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47261207/