lj_tang
lj_tang

Reputation: 21

How can I change an array into an object in jbuilder when it is the value of a key?

I'm using rails and I'm formatting the response with jbuilder and associations. Here is the code that I have

json.comments @post.comments.each do |comment|
   json.set! comment.id do 
      json.partial! 'api/comments/comment', comment: comment 
      json.author comment.commenter.email
   end 
end

post has many comments. So when I use that association it returns an array. I've been trying to get rid of it but I do not know where I'm doing it wrong.

Expected output:

{ 0:{
      id:0,
      author: 'Leon',
      comment: 'today is a good day',
     },
   1:{
      id: 1,
      author: 'John',
      comment: 'Game is on tonight',
     },
}

Current output:

[ 0:{
      id:0,
      author: 'Leon',
      comment: 'today is a good day',
     },
   1:{
      id: 1,
      author: 'John',
      comment: 'Game is on tonight',
     }
]

Upvotes: 0

Views: 135

Answers (1)

lj_tang
lj_tang

Reputation: 21

I found the answer. In order to be make it an object, I needed to add a do to the code:

 json.comments do
        @post.comments.each do |comment|
        json.set! comment.id do 
            json.partial! 'api/comments/comment', comment: comment 
            json.author comment.commenter.email
            end
        end
    end

Upvotes: 0

Related Questions