[英]How can I change an array into an object in jbuilder when it is the value of a key?
我正在使用 Rails,我正在使用 jbuilder 和關聯格式化響應。 這是我的代碼
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
帖子有很多評論。 因此,當我使用該關聯時,它會返回一個數組。 我一直試圖擺脫它,但我不知道我在哪里做錯了。
預計 output:
{ 0:{
id:0,
author: 'Leon',
comment: 'today is a good day',
},
1:{
id: 1,
author: 'John',
comment: 'Game is on tonight',
},
}
當前output:
[ 0:{
id:0,
author: 'Leon',
comment: 'today is a good day',
},
1:{
id: 1,
author: 'John',
comment: 'Game is on tonight',
}
]
我找到了答案。 為了使它成為 object,我需要在代碼中添加一個do
:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.