Rakesh Patidar
Rakesh Patidar

Reputation: 196

Get all posts with all comments 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"
        }
      ]
    }
  ]
}

Upvotes: 1

Views: 120

Answers (2)

ashishmax31
ashishmax31

Reputation: 171

Use activemodel Activemodel Serializers.Also check out this railscasts video which gives you a pretty good idea about activemodel serializers and how to use it Railscasts-activemodel serializers. Hope i've helped.

Upvotes: 0

Navin
Navin

Reputation: 924

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

Upvotes: 2

Related Questions