【发布时间】: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