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

时间:2018-04-18 03:47:26

标签: rails-api rails-activestorage ruby-on-rails-5.2

想要为附加文件添加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 个答案:

答案 0 :(得分:4)

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

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

所以,为了达到我所需的输出,我必须做

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

答案 1 :(得分:3)

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

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

在官方指南中说明=)

答案 2 :(得分: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