Pascal
Pascal

Reputation: 1178

(RoR) json and nested objects: get attribute in object of object

My goal is an output like this (for each attachment):

url: "/uploads/attachment/picture/15/5ee306c9-e263-466b-b56d-1c7c9d2ae17b.jpg"

What I have at the moment:

json object in object

attachments_controller.rb

class AttachmentsController < ApplicationController
  before_action :logged_in_user

  def index
    @attachments = current_user.attachments.all
    respond_to do |format|
      format.json do
        render :json => @attachments.each{ |o| o.picture.url }
      end
    end
  end

...

Upvotes: 0

Views: 156

Answers (1)

Matt Gibson
Matt Gibson

Reputation: 14959

Try

respond_to do |format|
  format.json do
    render :json => @attachments.map { |o| { url: o.picture.url } }
  end
end

Upvotes: 1

Related Questions