Getting Nested JSON Output from Rails

Suppose I have a Rails application with two models Postand Comment. Comments has_manyand comment belongs_topost.
How can I override a function respond_toin action showto get a JSON response containing both properties Postand an array of objects Commentthat it has?

This value is currently used for vanilla rails:

# 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
+3
source share
4 answers

This can be done using the Active Record serialization method.

to_json

Below code should work.

 format.json { render json: @post.to_json(:include => :comments) }
+3
source

active_model_serializers json. , , .

:

class PostSerializer < ApplicationSerializer
    attributes :id, :title, :body
    has_many :comments
end
+2

You can override to_jsonin the model or you can use Jbuilder or rabl .

+2
source

Rails provides the best way to respond:

Define reply_to at the top of your controller. eg:

class YourController < ApplicationController
  respond_to :xml, :json

  def show
    @post = current_user.posts.find(params[:id])
    respond_with (@post)
  end
end

For more information, see: http://davidwparker.com/2010/03/09/api-in-rails-respond-to-and-respond-with/

+1
source

All Articles