我正在将图像附件从React作为Blob发送到Rails Active Storage。一切都可以上传到AWS S3,但是返回的数据不适合使用<Image
进行渲染。
这是一个回到React的例子:
avatar: "/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2…736b6edc83b7ccfc91c7914d7eb595a697fb/IMG_2008.png"
我的User
模型如下:
class User < ApplicationRecord
include Rails.application.routes.url_helpers
has_secure_password
has_one_attached :avatar
def avatar_filename
self.avatar.filename.to_s if self.avatar.attached?
end
def avatar_attached?
self.avatar.attached?
end
has_many :sightings
has_many :animals, through: :sightings
has_many :comments, :as => :commentable, dependent: :destroy
validates :username, uniqueness: true
def attachment_url
if self.attachment.attached?
Rails.application.routes.url_helpers.rails_blob_path(self.attachement, only_path:true)
else
nil
end
end
end
和UserSerializer
看起来像这样:
class UserSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
attributes :id, :name, :username, :avatar
has_many :sightings
has_many :animals, through: :sightings
def avatar
rails_blob_path(object.avatar, only_path: true) if object.avatar.attached?
end
end
因此,我使用的是url_helper,但由于是newb,因此不确定是否使用正确,并且文档可能会造成混淆。