Rails 渲染中的活动存储图像 link json

Rails Active Storage image link in render json

如何用我的帖子(每个帖子都有一个附件)和他们的图片 url 渲染 json?

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

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

json.jbuilder 查看文件可以提供帮助

app/view/posts/index.json.jbuilder

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

app/view/posts/_post.json.jbuilder

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