Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting nested JSON output from Rails

Suppose I have a Rails app with two models Post and Comment. A post has_many comments and a comment belongs_to a post.
How can I override the respond_to function in the show action in order to get a JSON response containing both the Post properties and an array of Comment objects that it has?

Currently it is the vanilla Rails default:

# posts_controller.rb
def show
  @post = current_user.posts.find(params[:id])

  respond_to do |format|
    format.html # show.html.erb
    format.json { render json: @post }
  end
 end
like image 760
Andrew Lauer Barinov Avatar asked Apr 25 '26 03:04

Andrew Lauer Barinov


2 Answers

You can do that using Active Record serialization method.

to_json

Below code should work.

 format.json { render json: @post.to_json(:include => :comments) }
like image 197
Soundar Rathinasamy Avatar answered Apr 26 '26 20:04

Soundar Rathinasamy


Try using active_model_serializers for json serialization. It is easy to include associated objects and also separates things by having a different file for serialization.

Example:

class PostSerializer < ApplicationSerializer
    attributes :id, :title, :body
    has_many :comments
end
like image 33
johnmcaliley Avatar answered Apr 26 '26 18:04

johnmcaliley