首页 文章

Rails 5.2 Rest API Active Storage React - 将附件URL添加到控制器响应中

提问于
浏览
1

想要为附加文件添加url,同时响应获取父资源(比如Person)的嵌套资源(比如Document)的请求 .

# people_controller.rb  
def show
   render json: @person, include: [{document: {include: :files}}]
end


# returns
# {"id":1,"full_name":"James Bond","document":{"id":12,"files":[{"id":12,"name":"files","record_type":"Document","record_id":689,"blob_id":18,}]}


# MODELS
# person.rb  
class Person < ApplicationRecord
   has_one :document, class_name: "Document", foreign_key: :document_id
end

# document.rb
class Document < ApplicationRecord
   has_many_attached :files
end

问题是,我想在React前端设置中显示该文件或提供该文件的链接,该设置没有像url_for这样的辅助方法 . As pointed out here .

任何帮助将不胜感激 .

3 回答

  • 2

    在挖掘了Active Storage的source code之后,我发现了一些模型方法,这些方法使用了一个名为 service_url 的公开方法,该方法返回附件文件的短期链接 .

    然后this answer帮助在控制器响应json中包含该方法 .

    所以,为了实现我所需的输出,我必须这样做

    render json: @person, include: [{document: {include: {files: {include: {attachments: {include: {blob: {methods: :service_url}}}}} }}]
    
  • 4

    我所做的是在模型中创建此方法

    def logo_url
      if self.logo.attached?
        Rails.application.routes.url_helpers.rails_blob_path(self.logo, only_path: true)
      else
        nil
      end
    end
    

    要将logo_url添加到响应json,您可以添加 methods .

    render json: @person, methods: :logo_url
    

    这在官方指南中解释=)

  • 0
    class Meal < ApplicationRecord
      has_many_attached :photos
    end  
    
    class MealsController < ApplicationController
      def index
        render json: current_user.meals.map { |meal| meal_json(meal) }
      end
    
      def show
        render json: meal_json(current_user.meals.find!(params[:id]))
      end
    
      private
    
      def meal_json(meal)
        meal.as_json.merge(photos: meal.photos.map { |photo| url_for(photo) })
      end
    end
    

相关问题