繁体   English   中英

渲染 json 中的 Rails Active Storage 图像链接

[英]Rails Active Storage image link in render json

我怎么能用我的帖子(每个帖子都有一个附件)和他们的图片网址渲染一个json?

def index
  @posts = Post.all
  render json: { posts: @posts }, include: :image # Image is the attachment
end

我有这个,但我知道这行不通,因为我需要图片 URL

json.jbuilder 视图文件可以在这里提供帮助

应用程序/视图/帖子/index.json.jbuilder

json.array! @posts, partial: 'post', as: :post

应用程序/视图/帖子/_post.json.jbuilder

json.id post.id
json.image_url url_for(post.image) if post.image.attached?
//all other fields you need

Rails 是优雅的对立面。 在现代框架中,所有这些都不是必需的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM