以json格式获取包含所有评论的所有帖子(Get all posts with all comments in json format)

编程入门 行业动态 更新时间:2024-10-26 23:28:41
以json格式获取包含所有评论的所有帖子(Get all posts with all comments in json format)

我有两个模型Post和Comment

class Post < ActiveRecord::Base has_many :comments end class Comment < ActiveRecord::Base belongs_to :post end

如何获得所有带有评论的帖子,如下面的json响应:

{ "posts": [ { "name": "Ruby on Rails", "comments": [ { "desc": "awesome" } ] }, { "name": "Java", "comments": [ { "desc": "Thanks" }, { "desc": "very useful" } ] } ] }

I have two models Post and Comment

class Post < ActiveRecord::Base has_many :comments end class Comment < ActiveRecord::Base belongs_to :post end

How can I get all the posts with comments as below json response:

{ "posts": [ { "name": "Ruby on Rails", "comments": [ { "desc": "awesome" } ] }, { "name": "Java", "comments": [ { "desc": "Thanks" }, { "desc": "very useful" } ] } ] }

最满意答案

试试这个,在app / views / posts /中创建一个index.json.jbuilder,并添加以下代码

json.posts @posts do |post| json.name post.name json.comments post.comments do |comment| json.desc comment.desc end end

try this, create a index.json.jbuilder in app/views/posts/ , and add the following code to it

json.posts @posts do |post| json.name post.name json.comments post.comments do |comment| json.desc comment.desc end end

更多推荐

本文发布于:2023-07-30 11:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1337881.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:格式   帖子   json   format   comments

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!