你如何使用神社播种图像

时间:2017-11-13 09:41:54

标签: ruby-on-rails ruby-on-rails-5 shrine

我不能使用神社播种我的图像,不像载波,下面的代码不起作用。

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>'

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

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

1 个答案:

答案 0 :(得分:3)

使用Shrine,模型上的附件属性(例如image_data)(例如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)

这里上传者的主要方法是#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