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
0

4 Answers 4

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) }
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

2

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

Comments

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.