ruby-on-rails - 如何使用 Shrine 播种图像

标签 ruby-on-rails ruby-on-rails-5 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"))

但它返回

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 )是数据库中的文本列(您也可以将其定义为 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)

这里 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/

相关文章:

ruby-on-rails - 使用 Shrine 在文件夹之间移动 AWS S3 Bucket 上的文件

ruby - 使用 Shrine 让每个帐户都有一个单独的 S3 存储桶来存放附件

ruby-on-rails - rails : complicated design choice: polymorphism? STI?

css - 按 id 突出显示 Rails 3 中的当前页面

ruby-on-rails - 为什么在 rails 2 中使用 vpim 会出现编码错误?

ruby-on-rails - ActiveRecord::Relation 上下文中的独立 ActiveRecord 查询

ruby-on-rails - 在引发错误的方法中调用 RSpec 测试 Rollbar

ruby-on-rails - Rails 5 + Shrine 多文件上传

ruby-on-rails - 我是否正确地在 Heroku + Unicorn 中预加载了应用程序?

ruby-on-rails - paper_trail gem 使用 object_changes nil 保存版本