3

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
JJD
  • 50,076
  • 60
  • 203
  • 339
Andrew Lauer Barinov
  • 5,694
  • 10
  • 59
  • 83

4 Answers4

4

You can do that using Active Record serialization method.

to_json

Below code should work.

 format.json { render json: @post.to_json(:include => :comments) }
Soundar Rathinasamy
  • 6,658
  • 6
  • 29
  • 47
2

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
johnmcaliley
  • 11,015
  • 2
  • 42
  • 47
2

You can override to_json in model or you can use Jbuilder or rabl.

JJD
  • 50,076
  • 60
  • 203
  • 339
Amar
  • 6,874
  • 4
  • 25
  • 23
1

Rails has provide the best way to respond :

Define respond_to on the top of your controller . like :

class YourController < ApplicationController
  respond_to :xml, :json

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

For more info take a look on : http://davidwparker.com/2010/03/09/api-in-rails-respond-to-and-respond-with/

Vik
  • 5,931
  • 3
  • 31
  • 38