以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 endHow 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 endtry 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更多推荐
发布评论