Rakesh Patidar Rakesh Patidar - 1 month ago 8
JSON Question

Get all posts with all coments in json format

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"
}
]
}
]
}


Thanks in advance :)

Answer

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