简体   繁体   中英

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?

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

json.jbuilder view files can help here

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

Rails is literally the opposite of elegant. All of this should not be necessary in a modern framework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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