【问题标题】:How do you seed images using Shrine如何使用 Shrine 播种图像
【发布时间】:2018-04-25 22:49:24
【问题描述】:

我无法使用神社播种我的图像,与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"),
}

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

【问题讨论】:

  • 请分享 Profile 类定义以及 Shrine 初始化程序和 ImageUploader.rb
  • 好的,我已经添加了上面的额外信息。
  • 您在运行命令时是否收到任何错误消息?
  • 不是当我运行 db:seed 时,而是当我转到配置文件时它不会加载图像。 743:'#<0x007f83204b7800>

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


【解决方案1】:

使用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的对象,并在输出上返回上传文件的表示(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

【讨论】:

  • 有效!漂亮!
猜你喜欢
  • 2020-03-08
  • 1970-01-01
  • 1970-01-01
  • 2019-05-23
  • 2016-12-02
  • 2023-04-01
  • 1970-01-01
  • 2022-06-20
  • 2021-08-20
相关资源
最近更新 更多