【问题标题】:Rails API Image Upload with Active Storage / S3, React and ActiveAdmin使用 Active Storage / S3、React 和 ActiveAdmin 上传 Rails API 图像
【发布时间】:2020-04-30 15:45:36
【问题描述】:

我使用 Rails API 创建了一个应用程序,该 API 具有 React 前端和 ActiveAdmin 作为 CMS 后端,它基于 this tutorial。我正在添加一个模型,其中包含使用 ActiveStorage 进行文件上传的图像,以及用于生产存储的 S3。

app/models/photo.rb

class Photo < ApplicationRecord
    has_one_attached :image
end

app/controllers/photos_controller.rb

class PhotosController < ApplicationController
  include ActionController::Serialization
  before_action :set_photo, only: [:show, :update, :destroy]

  # GET /photos
  def index
    @photos = Photo.all
    render json: @photos.to_json
  end

  ...

  def photo_params
    params.require(:photo).permit(:image, :location_name, :region, :url)
  end
end

app/serializers/photo_seralizer.rb

class PhotoSerializer < ActiveModel::Serializer
  attributes :id, :image, :location_name, :region, :url

  def image
    rails_blob_path(object.image, only_path: true) if object.image.attached?
  end
end

当我查看 API 端点时,附加的图像没有显示在照片对象中,这是一个示例返回。序列化器中是否缺少我在相关图像中未添加的内容?任何帮助将不胜感激,谢谢!

[{
  "id":1,
  "location_name":"Acreage Ciderhouse",
  "region":"Northern Metro",
  "url":"https://example.com/acreage-ciderhouse/",
  "created_at":"2020-01-09T15:18:33.298-07:00",
  "updated_at":"2020-01-09T15:27:40.594-07:00"
}]

【问题讨论】:

    标签: ruby-on-rails serialization rails-api


    【解决方案1】:

    activestorage 保存数据的方式不同,我认为您的索引是从您的模型表中调用数据,但图像是与其他表相关的。因此,以下是检查图像是否真的保存的方法,使用 rails 控制台进行检查。

    rails c
    @photo = Photo.find(1)
    puts @photo.image.attached?
    

    如果您确定图像现在正确保存,您可以执行以下操作以在您的请求中添加所有图像网址

    def index
    @photos = Photo.all
    @photos.each do |p|
       if @photo.present? 
         image_url = { :image => (url_for p.image) }
         p.attributes.merge(image_url)
        end
    end
    render json: @photos.to_json
    end
    

    我没有测试上面的代码,只是写了,但是我在我的api中使用了很多。

    【讨论】:

      猜你喜欢
      • 2019-11-19
      • 2021-04-15
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      相关资源
      最近更新 更多