Search code examples
ruby-on-railsrails-activestorage

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


Solution

  • 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