简体   繁体   English

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

[英]Rails Active Storage image link in render json

How could I render a json with my posts (each one have an attachment) with their image url?我怎么能用我的帖子(每个帖子都有一个附件)和他们的图片网址渲染一个json?

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

I have this, but I know this is not going to work due to I need the image URL我有这个,但我知道这行不通,因为我需要图片 URL

json.jbuilder view files can help here json.jbuilder 视图文件可以在这里提供帮助

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

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

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

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

Rails is literally the opposite of elegant. Rails 是优雅的对立面。 All of this should not be necessary in a modern framework.在现代框架中,所有这些都不是必需的。

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

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