如何在Rails的Jbuilder中将关联数组转为对象作为键值?
解决Jbuilder将评论关联转为对象格式的问题
你的问题出在json.comments的写法上,当前代码把@post.comments.each作为参数传给json.comments,而each返回的是原数组,导致Jbuilder默认渲染成数组结构。要生成对象格式,需要调整代码结构:
修改后的代码
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
原理说明
- 原写法中,
json.comments @post.comments.each会让Jbuilder把comments字段识别为数组类型,因为传入的是数组对象。 - 修改后,
json.comments后面紧跟一个块,Jbuilder会先创建一个空对象,然后在块内部通过json.set! comment.id为这个对象逐个添加键值对,最终生成你预期的以评论ID为键的对象结构。
内容的提问来源于stack exchange,提问作者lj_tang
相关产品推荐
相关产品推荐

