想要为附加文件添加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 回答
在挖掘了Active Storage的source code之后,我发现了一些模型方法,这些方法使用了一个名为 service_url 的公开方法,该方法返回附件文件的短期链接 .
然后this answer帮助在控制器响应json中包含该方法 .
所以,为了实现我所需的输出,我必须这样做
我所做的是在模型中创建此方法
要将logo_url添加到响应json,您可以添加
methods
.这在官方指南中解释=)