Reputation: 196
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
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
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